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?

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.