javascript - Parse Json Array in jQuery -
i new jquery , java script. need parse json file has arrays, use 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 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 result is:
materials [object object]   how can change code objects when loop meets them?
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 check value 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 $.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>');     } });      
Comments
Post a Comment