需要解析复杂的Json

时间:2013-04-05 10:54:16

标签: javascript json

我和json数据从服务器获取,努力解析JavaScript中的json,因为它不是一个直接的json。这是样本

[
   {
      "target":"collectd.matrix.oracle.avg_resp_time",
      "datapoints":[
         [8.0, 1365158480],
         [null, 1365158490],
         [null, 1365158500],
         [null, 1365158510],
         [null, 1365158520],
         [null, 1365158530],
         [8.0, 1365158540],
         [null, 1365158550],
         [null, 1365158560],
         [null, 1365158570],
         [null, 1365158580],
         [null, 1365158590],
         [8.0, 1365158600],
         [null, 1365158610],
         [null, 1365158620],
         [null, 1365158630],
         [null, 1365158640],
         [null, 1365158650],
         [8.0, 1365158660],
         [null, 1365158670],
         [null, 1365158680],
         [null, 1365158690],
         [null, 1365158700],
         [null, 1365158710],
         [null, 1365158720],
         [null, 1365158730],
         [null, 1365158740],
         [null, 1365158750],
         [null, 1365158760],
         [null, 1365158770]
      ]
   }
]

在这里,我还需要捕获每个字段的值,如eg:X=8.0,Y=1365158540

需要一些帮助或逻辑来解析它。

谢谢, sohan

3 个答案:

答案 0 :(得分:2)

原生JSON.parse()应该可以正常使用。使用json2.js可在旧版浏览器中向后兼容。这是一个例子:

var data = JSON.parse(yourJsonGoesHere),
    datapoints = data[0].datapoints,
    i;

for (i = 0; i < datapoints.length; ++i) {
    console.log('x:' + datapoints[i][0] + ', y:' + datapoints[i][1]);
}

答案 1 :(得分:2)

var jsonData = JSON.parse(data)

,其中

data = '[{"target": "collectd.matrix.oracle.avg_resp_time", "datapoints": [[8.0, 1365158480], [null, 1365158490], [null, 1365158500], [null, 1365158510], [null, 1365158520], [null, 1365158530], [8.0, 1365158540], [null, 1365158550], [null, 1365158560], [null, 1365158570], [null, 1365158580], [null, 1365158590], [8.0, 1365158600], [null, 1365158610], [null, 1365158620], [null, 1365158630], [null, 1365158640], [null, 1365158650], [8.0, 1365158660], [null, 1365158670], [null, 1365158680], [null, 1365158690], [null, 1365158700], [null, 1365158710], [null, 1365158720], [null, 1365158730], [null, 1365158740], [null, 1365158750], [null, 1365158760], [null, 1365158770]]}]';

jsonData[0]['datapoints']是所有数据点的数组

Reference for JSON.parse

答案 2 :(得分:1)

如果你通过ajax获得回复,你可以在你的ajax调用中添加datatype:json

OR

您可以使用http://api.jquery.com/jQuery.parseJSON/

var obj = jQuery.parseJSON(jsonString)