1

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
asked Mar 7, 2015 at 23:00
1
  • The posted code actually doesn't reach the $.each because there is a syntax error. That being said, j.firstName is what you want. $.getJSON parses the responseText for you! Commented Mar 7, 2015 at 23:11

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.