【问题标题】:Retrieving individual fields from JSON file in Javascript [closed]在Javascript中从JSON文件中检索单个字段[关闭]
【发布时间】:2013-06-12 16:01:38
【问题描述】:

我正在使用主干、jquery、下划线,我想获取一些我在本地文件中得到的 JSON。

我正在使用

        //Will get data but no access to individual objects
        $.getJSON('carinfo.json', function(data){
            console.log(data);
            var data2 = data['unitId'];
            console.log(data2);


        });

将 JSON 提取到数据变量中,但我不知道从哪里开始。例如,我将如何从字段名称“carID”中取回所有值?

这是我的一个 JSON 条目的样子

{
    "carID": "xx",
    "xxx": {
        "unitID": "xxxxxxx",
        "positionHistory": [{
            "lat": "xxxxx",
            "long": "xxxxxxxx",
            "time": "xxxxxxxxxx",
            "status": "1",
            "estimatedSpeed": "0",
            "lastSoundFileName": "xxxxx",
            "lastSoundRange": "12",
            "lastSoundTime": "xxxxxxxx",
            "isToday": false,
            "minutesAgo": xxxxxx
        }]
    },
    "registration": "xxxxxxx",
    "color": "xxxxxxxx",
    "phone": "",
    "model": "xxxx"
}

编辑:使用 data.carID 返回未定义。

chrome 控制台输出截图

【问题讨论】:

标签: javascript jquery json backbone.js


【解决方案1】:

更新以说明您的数据是一个数组。

$.getJSON('carinfo.json', function (data) {
    // Loop over all the cars in data
    for (var i = 0; i < data.length; i++) {
        var car = data[i];
        car.carID === 'xx';  // just do data.whatever to get the value
        car.phone === '';

        car.xxx.positionHistory[0].status === '1'; // data.xxx.positionHistory is an array;
                                            // use [i] to get the ith element

        car.xxx['unitID'] === 'xxxxxxx';     // You can use bracket notation with a
                                      // string to get an object property if
                                      // you prefer

    }
});

【讨论】:

    【解决方案2】:

    如果您的 JSON 是一个汽车条目数组,那么您需要这样访问它们:

    $.getJSON('carinfo.json', function (data) {
        for(var i=0; i<data.length; i++) {
            console.log(data[i].carID);
        }
    
        // or access without a loop:
        console.log(data[0].carID);
        console.log(data[1].carID);
        console.log(data[0].xxx.unitID);
    }); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-10
      • 1970-01-01
      相关资源
      最近更新 更多