1

我是 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]

如何更改我的代码,以便在循环遇到对象时也能获得对象?

4

2 回答 2

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>');
    }
});
于 2013-08-08T08:10:42.593 回答
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);
         });
     });    


});
于 2014-01-30T07:24:45.177 回答