Access array-elements inside JSON-object - javascript

I have the following json-object returned via response
the function
function getUserList() {
$.ajax({
url: "https://reqres.in/api/users",
type: "POST",
data: {
name: "paul rudd",
movies: ["I Love You Man", "Role Models"]
},
success: function(response){
console.log(response); // prints the object
}
});
}
My question is how the movies-array are accessed in javascript? I cannot access it via response - if I do i get "undefined" returned.
i.e response.movies
undefined
or response.movies[0]
uncaught typerror cannot read property [0] of undefined

The property of the object appears to be "movies[]", not "movies", for which you can use bracket notation to get the value of
console.log(response["movies[]"][0])

Try response['movies[]']. Also, you could console log the response object and inspect what is inside it

in your back end you're returning with bad naming , so
to access that array you've to access it as below response.["movies[]"]
see below sample :
response = { "movies[]": ["1","2","3"] };
console.log(response["movies[]"]);

movies is array, use $.each or .forEach()
$.ajax({
url: "https://reqres.in/api/users",
type: "POST",
data: {
name: "paul rudd",
movies: ["I Love You Man", "Role Models"]
},
success: function(response) {
$.each(response.movies, function(index, value){
// prints the object
console.log(value);
})
}
});

Related

Can not get value from JSON object

I'm having trouble getting the data value from JSON object. Here is my code:
var ab_id = $( "#ab_id" ).val();
$.ajax({
type: 'GET',
contentType: 'application/json',
url: 'edit_account.php',
data: {ab_id:ab_id, u_id:u_id},
success: function(data)
{
alert(data.ab_name);
},
});
When I do alert(data), I got the actual data like this:
{
"ab_id":"7",
"ab_name":"Lily's Storage Address",
"ab_ship_name":"LIly C\/O SELF STORAGE",
"ab_addr_1":"C\/O Lily",
"ab_addr_2":"16 PIUMA AVENUE, UNIT #2",
"ab_city":"CERI",
"ab_state":"CA",
"ab_postal":"90700",
"ab_phone":null,
"ab_default":"0",
"ab_is_storage":"1"
}
However, when I retrieve the data value by using data.ab_name, it returns undefined.
Am I missing something here?
Use bracket notation
alert(data['ab_name']);
for reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors
Parse your string to a object
data = JSON.parse(data);
alert(data.ab_name);

Why does my JSON data with Ajax not return correctly even though the console logs it?

I am getting a number (1,2,3, etc.) based on coordinates like this:
function getNumber(lat,lng)
{
var params="lat="+lat+"&long="+lng;
$.ajax({
type: "POST",
url: "https://www.page.com/code.php",
data: params,
dataType: 'json',
success: function(data){
if (data.valid==1){
console.log(data);
$("#number").html(data.number);
} else {
console.log(data);
}
},
error: function(){
}
});
}
The problem is, when I check the console, the data is there like this:
[Object]
0 Object
lat: 100.00
long: 50.00
number: 1
etc.
Why doesn't it let me parse it?
The way I return it with POST is:
[{"valid":"1","lat":100.00,"long":50.00,"number":"1"}]
So you are returning an array?
Then you need to refer to the data by index:
data[0].valid==1

Undefined when trying to parse JSON

I'm trying to parse a JSON response with JQuery:
<script>
$(document).ready(function() {
$("button").click(function() {
$.ajax({
url : 'test.php',
type : 'GET',
data : {
name : "Peter",
},
dataType : 'json',
success : function(response) {
console.log(response);
alert(response.name)
},
error : function() {
console.log("error")
}
});
});
});
</script>
I want to get the name into the alert box, but everything I get is an undefined.
This is the result in the console:
Object {results: Array[1]}
results: Array[1]
0: Object
id: "4"
name: "Peter"
When I do alert(JSON.stringify(response)); I get {"results":[{"id":"4","name":"Peter"}]}, so there is definitely valid JSON.
In response there is not property name. name there is in in first element in results array, so to get name you need do
console.log(response.results[0].name)
response is an object which contains an array in results, you need to iterate over ressponse.results or if you're sure it well have only one element, use response.results[0].name
The JSON data contains an array, so you need use an index:
var data = {"results":[{"id":"4","name":"Peter"}]}
document.write(data.results[0].name)

Parsing JSONP file with JavaScript

How do I access the Marie-Antoinette.json object in this JSON file? I would like to get the title element of the object but I can't seem to get it to output. Here is my JavaScript code which outputs the object but I cant seem to access the objects elements.
$.ajax(
{
type: 'GET',
url: 'http://localhost:5984/movies/efadd5913f5cfd254b2861efd4001cb7',
//contentType: "application/json; charset=utf-8",
dataType: "JSONP",
jsonpCallback: 'callback',
//async: false,
success: function(r)
{
alert("ok");
$.each(r, function(index, value){ // iterating over each object
console.log(index);
if(index == "_attachments")
{
console.log(value); //how do I output the title ("Marie-Antoinette.json") and the other stuff in the object?
}
});
}
});
Here is the file. The elements I would like to access are in the "_attachments" element of the object.
{
"_id": "efadd5913f5cfd254b2861efd4001cb7",
"_rev": "6-417588bbff9aa74726b11440a86a8532",
"_attachments": {
"Marie-Antoinette.json": {
"content_type": "application/json",
"revpos": 2,
"digest": "md5-Io/Pxakfp/4R8ntjQKWMDg==",
"length": 761,
"stub": true
}
}
}
I think what is throwing me off is that it is an object inside the _attachment section.
The Marie-Antoinette.json object is inside your _attachments object, but because it contains a . it can't be accessed using dot-notation. You'll have to use array-like notation, passing the key as a string like so:
success: function (response) {
console.log(response._attachments['Marie-Antoinette.json']);
}
If you have multiple "attachments", you can access them in a loop like this:
success: function (response) {
$.each(response._attachments, function (i, attachment) {
console.log(attachment);
});
}
You could use Object.keys to extract keys from _attachments object and then print it:
var title = Object.keys(r._attachments)[0];
console.log(title);
Or if you have multiple attachments:
var titles = Object.keys(r._attachments);
console.log(titles.join());
Object.keys always returns an array.
in your function:
success: function(r)
{
for (key in json._attachments) {
console.log(key); // gives the names
console.log(json._attachments[key]); // gives the content
}
}
that would give you the stuff in _attachments

Unable to get value from json object

I am trying to get a value from a json object after making an ajax call. Not sure what I am doing wrong it seems straight forward but not able to get the data
The data that comes back looks like this
{"data":"[{\"Id\":3,\"Name\":\"D\\u0027Costa\"}]"}
The code, removed some of the code
.ajax({
type: 'POST',
url: "http://localhost:1448/RegisterDetails/",
dataType: 'json',
data: { "HomeID": self.Id, "Name": $("#txtFamilyName").val()},
success: function (result) {
console.log(result.data); //<== the data show here like above
alert(result.data.Id); //<==nothing show
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I tried in the Chrome console like this
obj2 = {}
Object {}
obj2 = {"data":"[{\"Id\":3,\"Name\":\"D\\u0027Costa\"}]"}
Object {data: "[{"Id":3,"Name":"D\u0027Costa"}]"}
obj2.data
"[{"Id":3,"Name":"D\u0027Costa"}]"
obj2.data.Id
undefined
obj2.Id
undefined
Update
The line that solved the issue as suggested here is
var retValue = JSON.parse(result.data)[0]
Now I can used
retValue.Name
to get the value
Actually, looking at this, my best guess is that you're missing JSON.parse()
.ajax({
type: 'POST',
url: "http://localhost:1448/RegisterDetails/",
dataType: 'json',
data: { "HomeID": self.Id, "Name": $("#txtFamilyName").val()},
success: function (result) {
var javascriptObject = JSON.parse(result);
console.log(javascriptObject ); //<== the data show here like above
alert(javascriptObject.Id); //<==nothing show
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I also find that doing ajax requests like this is better:
var result = $.ajax({
url: "someUrl",
data: { some: "data" },
method: "POST/GET"
});
result.done(function (data, result) {
if (result == "success") { // ajax success
var data = JSON.parse(data);
//do something here
}
});
For clarity it just looks better, also copying and pasting into different functions as well is better.
The id property is in the first element of the data-array. So, alert(result.data[0].Id) should give the desired result. Just for the record: there is no such thing as a 'JSON-object'. You can parse a JSON (JavaScript Object Notation) string to a Javascript Object, which [parsing] supposedly is handled by the .ajax method here.
The data field is just a string, you should parse it to a JSON object with JSON.parse(result.data), since data is now an array you will need to need to use an index [0] to have access to the object. Know you will be able to get the Id property.
JSON.parse(result.data)[0].Id

Categories

Resources