javascriptjqueryjsonremoteobject

Reading object in json using jquery


i have below json which i get from Remote.

{

    "name":"planning Diet",
    "day1":{
        "morning":"chicken",
        "evening":"mutton",
        "night":"Juice"
    },
    "day2":{
        "morning":"burger",
        "evening":"pizza",
        "night":"Juice",
        "late night":"water"
    }

}

Below is what i tried.

$.getJSON("http://domain.com/hello.json",function(result){
  $.each(result, function(i, field)
{
console.log(field);
});

This returns something like

"planning diet"
[object object]
[object object]

Now how can i traverse or loop through all the object... ?


Solution

  • In your case you can use something like this,

    $.getJSON("http://domain.com/hello.json", function(result) {
        $.each(result, function(i, field) {
            if (typeof field == "object") {
                console.log(i);  
                $.each(field, function(i, f) {
                    console.log(f);
                });
            }
            else {
                console.log(field);
            }
        });
    });
    

    You can use typeof field == "object" to check the current item is an object or not