How can I read a nested json with ajax?
I have a json formatted by php after a sql request as follow :
[
{
"owner_info":
{
"name":"John",
"address":"4",
"date":"10/01/2012"
}
},
{
"telephone":
[
{
"id":"1",
"place":"5",
"number":"+123456"
},
{
"id":"2",
"place":"5",
"number":"+789456"
},
{
"id":"3",
"place":"8",
"number":"+0011223"
},
]
}
]
Ajax do a classic
$.getJSON(script, function (result) {
$(result).each(function(i){
// do something with result
});
});
I tried :
result[i].owner_info.name -> error
result[i].telephone[0].id -> error
I have been searching on the internet but can't find any solution...
thank you
You are using the wrong each
method. $(selector).each()
is not the same as $.each()
!
From the jQuery documentation.
The
$.each()
function is not the same as$(selector).each()
, which is used to iterate, exclusively, over a jQuery object. The$.each()
function can be used to iterate over any collection, whether it is a map (JavaScript object) or an array.
A solution using the correct each
function.
$.getJSON(script, function (result) {
$.each(result, function(key, value) {
// either use
console.log(value.owner_info.name);
// or
console.log(result[key].owner_info.name);
});
});