1

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

1 Answer 1

2

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

5 Comments

thanks but i still get the same error in javascript : owner_info.name is null or not an object is there something wrong with nesting json like that ?
Then result is not in the format you specified! I create a jsfiddle with the data you gave and it works!
I just realised that the part trying to read the telephone is the one firing the error. I'm trying value.telephone[1].number but javascript error as above
Now after a second look on your data I see that your array contains 2 objects. One object is owner_info and the other object is telephone. From what you have tried it seems you want to have telephone be in the owner_info object, not the second element of the result array. The code above will also fail for the second element in the array because it has no property called name.
what i want to achieve is something like [ owner_info, telephone[] ] -> an entry has 1 owner_info and n telephone. How can I achieve that ?

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.