I am trying to parse a JSON result with AJAX.
My JSON looks like this
[{
"_id" : "54fb09b7d059bdf3107f9486",
"lastName" : "Record",
"firstName" : "First",
"__v" : 0
}, {
"_id" : "54fb0a2fd059bdf3107f9487",
"lastName" : "Record",
"firstName" : "First",
"__v" : 0
}
]
I call this in Javascript
$.getJSON('api/people', function(data) {
item3="+data.item3+"</p>");
$.each(data,function(i,j){
content ='<span>'+j[i].firstName+'<br />'+j[i].lastName+'<br /></span>';
});
alert(content);
});
Unfortunately I get "Uncaught TypeError: Cannot read property 'firstName' of undefined" in the console.
Can someone please tell me how to properly parse this JSON?
JFK
41.2k31 gold badges138 silver badges314 bronze badges
1 Answer 1
jQuery.each's second argument (the function executed for each element) takes two arguments (in your example, i and j), the first representing the key and the second the value, so there's no need for j[i].
This should work:
$.getJSON('api/people', function(data) {
$.each(data,function(i, item){
content ='<span>'+item.firstName+'<br />'+item.lastName+'<br /></span>';
});
alert(content);
});
answered Mar 7, 2015 at 23:10
instanceofnull
1,0811 gold badge7 silver badges15 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js
$.eachbecause there is a syntax error. That being said,j.firstNameis what you want.$.getJSONparses theresponseTextfor you!