1

Hi friend I'm learing hoq jSON works I create file named demo_ajax_json.js which has following code

[
{ 
  "firstName": "John",
  "lastName": "Doe",
  "age": 25
},
{ 
  "firstName": "SAM",
  "lastName": "Doe",
  "age": 36
},
{ 
  "firstName": "MAX",
  "lastName": "Doe",
  "age": 55
}
]

I'm tryiung to fetch firstName and age only. I wrote following code

function json(){
$.getJSON( "demo_ajax_json.js", function( data ) {
    var items = [];
    $.each( data, function( firstName, age) {
    $("div ul").append( "<li id='" + firstName + "'>" + age+ "</li>" );
    });

});
    }

$(document).ready(function(){
  $("button").click(function(){

      json();
  });
});

And this code giving me this

[object Object]
[object Object]
[object Object]

Plz help guys how to get this done.

Thanks in advance

2 Answers 2

1
...        
var items = [];
$.each( data, function(index, value) {
  $("div ul").append( "<li id='" + value.firstName + "'>" + value.age+ "</li>" );
});
...
Sign up to request clarification or add additional context in comments.

Comments

0

Your code should be this:

function json(){
  $.getJSON( "demo_ajax_json.js", function( data ) {
    var items = [];
    $.each( data, function(i,obj) {
    $("div ul").append( "<li id='" + obj.firstName + "'>" + obj.age+ "</li>" );
    });

  });
}

4 Comments

What's var items = []; for?
@GaryLuck this is used by OP. that's why I have remain it as it is.
Whoops! Thought I was commenting on OP. (Am on mobile) Though now that I look, OP is also not using It for anything. Does it need to be there?
@GaryLuck May be or may be not. depend on OP requirement.

Your Answer

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.