通过访问另一个JSON对象中的变量键来创建新的JSON对象

时间:2009-06-05 22:01:21

标签: javascript json

我正在尝试使用现有的JSON对象并从中创建更小的JSON块,特定于创建单独的图形。这是我使用jQuery的代码:

function updateStationGraphs (bsid) {
    $.getJSON("includes/system/ajaxDataInterface.php", {format:'flot',target:bsid}, function(data) {
        var graphOptions = {
            series: {
              lines: { show: true },
              points: { show: true }
            }
          };
        var handsetData = new Array(data[bsid].maxHandsets,data[bsid].avgHandsets);
        $.plot($('.graphHandsets'),handsetData,graphOptions);
    });

}

澄清:手机数据期待的格式是:

  [ { label: "Foo", data: [ [10, 1], [17, -14], [30, 5] ] },
    { label: "Bar", data: [ [11, 13], [19, 11], [30, -7] ] } ]

我的问题是,例如,当调用updateStationGraphs('A5A50000')时,它报告数据[bsid]未定义。我以前遇到过类似的问题,但我的问题是我再次重新声明我的'数据'对象而且正在玩错误的对象。这似乎不是这里的情况,我无法弄清楚为什么它不会让我访问数据[bsid]。

以下是数据的假设:

var data = {"A5A50000":{"time":{"label":"time","data":[[1244045863,"2009-06-03 16:17:43"],[1244045803,"2009-06-03 16:16:43"],[1244045743,"2009-06-03 16:15:43"],[1244045683,"2009-06-03 16:14:43"],[1244045623,"2009-06-03 16:13:43"],[1244045563,"2009-06-03 16:12:43"],[1244045503,"2009-06-03 16:11:43"],[1244045443,"2009-06-03 16:10:43"],[1244045383,"2009-06-03 16:09:43"],[1244045323,"2009-06-03 16:08:43"]]},"avgHandsets":{"label":"avgHandsets","data":[[1244045863,204.7143],[1244045803,205.9444],[1244045743,205.3333],[1244045683,205.3889],[1244045623,204.5882],[1244045563,204.8235],[1244045503,205],[1244045443,205.9412],[1244045383,205.6667],[1244045323,204.1176]]},"maxHandsets":{"label":"maxHandsets","data":[[1244045863,314],[1244045803,314],[1244045743,315],[1244045683,315],[1244045623,315],[1244045563,314],[1244045503,314],[1244045443,316],[1244045383,316],[1244045323,312]]}}};

非常感谢您的建议。提前谢谢。

2 个答案:

答案 0 :(得分:2)

我测试了你的代码,一切都很好。我在$.getJSON()调用后正确生成了flot图。

您需要确保返回的JSON数据在结尾处确实包含变量声明和分号。

换句话说,它应该只是JSON。

{"A5A50000":{"time":{"label":"time","data":[[1244045863.........]}}}

而不是:

var data = {"A5A50000":{"time":{"label":"time","data":[[1244045863,....

这可能是问题所在。

答案 1 :(得分:0)

事后看来,在休息和重新开始后,我能够意识到当bsid ='a5a50000'而不是bsid ='A5A50000'时我正在访问数据[bsid]。 总是检查你的情况! 叹息