2

I'm trying to read the value of a json nested object.
I have tried in these ways but without success.

data

{ "foo":  1,
  "bar": 10,
  "rows": [ {"id":1,"name":"Luke" },
            {"id":2,"name":"Sky" },
            {"id":3,"name":"Walker"} ]
}

Ajax

$.ajax({
    data: params,
    dataType: 'json',
    success: function(data) {

        console.log(data.rows) // data of rows object - OK !
        console.log(data["rows"].id); // undefined
        console.log(data.rows.id); // undefined
    }
});

How could I do? Thank you

Gus
  • 913
  • 2
  • 15
  • 30
  • Cannot comment yet, but your question seems to be a duplicate of http://stackoverflow.com/questions/4017122/jquery-reading-nested-json – ngn Jul 15 '15 at 12:37
  • Strongly suggested reading http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json – charlietfl Jul 15 '15 at 12:38

2 Answers2

2

Rows is an array.

Change

console.log(data["rows"].id);

to

console.log(data["rows"][0].id);

You can also iterate on it to get all the values

for (var i = 0; i < data["rows"].length; i++) {
    console.log(data["rows"][i].id); 
}
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
1

Data.rows is array of objects It should be accessed in other way

 $.ajax({
        data: params,
        dataType: 'json',
        success: function(data) {

            console.log(data.rows) // data of rows object - OK !
          $.each( data.rows, function( key, value ) {
      console.log( key + ": " + value );
       });

        }
    });
Shubham Nigam
  • 3,844
  • 19
  • 32