Parse Json Array in jQuery

I am new to jQuery and Java script. I need to parse a JSON file that has arrays, I use this code:

$.getJSON('mat.json', function(data) {
    var items = [];
    $.each(data, function(key, val) {
        items.push('<li id="' + key + '">' + val + '</li>');
    });

    $('<ul/>', {'class': 'my-new-list', html: items.join('')}).appendTo('body');
});

For this JSON file:

{
    "@file_name": "materials",
    "materials": [{
        "@site_name_English": "N/A",
        "@site_name_Spanish": "N/A",
        "@site_number": "1",
        "zoom": [{
            "@zoom_name_English": "Main Reservoir",
            "@zoom_name_Spanish": "DepĆ³sito principal",
            "@zoom_number": "1",
            "icon": [
                {
                    "@icon_name": "Info Icon 1",
                    "@icon_pin": "1"
                },
                {
                    "@icon_name": "Info Icon 2",
                    "@icon_pin": "2"
                }
            ]
        }]
    }]
}

But my result is:

materials
[object Object]

How can I change my code so I will get the objects also when the loop meets them?

Answers


Use this:

$.each(data, function(key, val) 
{
    if(typeof val === 'object') {
         $.each(val, function(keys, value) 
         {
         items.push('<li id="' + keys + '">' + value + '</li>'); 
         }
    } else {
       items.push('<li id="' + key + '">' + val + '</li>');
    }
});

You need to check that value is object or not.

EDITED:

function checkObj(key, val, items){
   if(typeof val === 'object') {
         $.each(val, function(keys, value) 
             {
            if(typeof value === 'object') {
                checkObj(keys, value, items);  
            } else {
               items.push('<li id="' + keys + '">' + value + '</li>'); 
            }
        });
    } 
}

And in the $.each function use this:

$.each(data, function(key, val) 
{
    if(typeof val === 'object') {
         checkObj(key, val, items);
    } else {
       items.push('<li id="' + key + '">' + val + '</li>');
    }
});

The program shows how to read json and store data into textbox

$(document).ready(function(){

$.getJSON("Test.json",function(data){

         $.each(data,function(key,value){
             alert(data[key].attrib1name);
             alert(data[key].attrib2name); 
             $('input').val(data[key].enterpriseName);
             activities=data[key].activities;
             console.log(value);
         });
     });    


});

Need Your Help

Remove a view from one view and add it to another

ios objective-c uiview addsubview

I am trying to find all my views that are in the nib and add them to my content view.

Reload div and posting data to that same div

jquery html

the below code works just fine for me but i ALSO want to reload the feed_back DIV every 3 seconds how can i do this please help