在jQuery中解析Json数组

时间:2013-08-08 08:01:49

标签: javascript jquery json

我是jQuery和Java脚本的新手。我需要解析一个包含数组的JSON文件,我使用这段代码:

$.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');
});

对于此JSON文件:

{
    "@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"
                }
            ]
        }]
    }]
}

但我的结果是:

materials
[object Object]

如何更改我的代码,以便在循环符合它们的同时获取对象?

2 个答案:

答案 0 :(得分:1)

使用此:

$.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>');
    }
});

您需要检查该值是否为对象。

<强>编辑:

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>'); 
            }
        });
    } 
}

在$ .each函数中使用:

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

答案 1 :(得分:0)

该程序显示如何读取json并将数据存储到文本框

$(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);
         });
     });    


});