如何在javascript中解析嵌套的json

时间:2014-11-13 07:21:09

标签: javascript json

我有一个类似

的Json数据
   [{
       "IncidentDate": "11/11/2014",
       "ComputerHits": [{
           "Computer": "abc",
           "Hits": 1
       }, {
           "Computer": "contoso-cscoISE-syslg",
           "Hits": 27
       }]
   }, {
       "IncidentDate": "11/12/2014",
       "ComputerHits": [{
           "Computer": "abc",
           "Hits": 9
       }, {
           "Computer": "contoso-cscoISE-syslg",
           "Hits": 66
       }]
   }]

我如何在javascript中将它们解析为数组,就像它基于日期

分开一样
abc= [{Hits:1},{Hits:9}]

contoso-cscoISE-syslg = [{Hits:27},{Hits:66}]

将它们添加到jqx图表中,任何人都可以帮助

2 个答案:

答案 0 :(得分:1)

要将JSON字符串解析为JS对象,请使用JSON.parse,如下所示;

var obj=JSON.parse(str)

之后,您应该能够重新格式化为您想要的任何内容。

<小时/> 对于您的确切应用,我们将逐步完成此步骤,
1.将字符串解析为对象

var obj=JSON.parse(str);

2。迭代你的价值观

for(var i=0;i<obj.length;i++){
  for(var j=0;j<obj[i]["ComputerHits"].length;j++){
    //Here will go some more code
  }
}

3。现在将值添加到正确的变量

window[obj[i]["ComputerHits"][j]["Computer"]].push({Hits:obj[i]["ComputerHits"][j]["Hits"]})

现在一起;

var obj=JSON.parse(str);
for(var i=0;i<obj.length;i++){
  for(var j=0;j<obj[i]["ComputerHits"].length;j++){
        window[obj[i]["ComputerHits"][j]["Computer"]].push({Hits:obj[i]["ComputerHits"][j]["Hits"]})
  }
}

答案 1 :(得分:1)

我刚刚写了这篇文章,它会分离点击并给你。

&#13;
&#13;
function custom_parser(A)
{
 var one = {};
 var two = {}; 
 for(var i = 0; i<A.length ; i++)
  {
    var current = A[i];
    var comp = current.ComputerHits;
    //comp is an array
    if(comp[0].Computer in one)
    {
      one[comp[0].Computer].push(comp[0].Hits);
    } 
    else
    {
      one[comp[0].Computer] = [comp[0].Hits];
    }
    if(comp[1].Computer in two)
    {
      two[comp[1].Computer].push(comp[1].Hits);
    } 
    else
    {
      two[comp[1].Computer] = [comp[1].Hits];
    }
  }
 return {one:one,two:two};
}

var B = [{
       "IncidentDate": "11/11/2014",
       "ComputerHits": [{
           "Computer": "abc",
           "Hits": 1
       }, {
           "Computer": "contoso-cscoISE-syslg",
           "Hits": 27
       }]
   }, {
       "IncidentDate": "11/12/2014",
       "ComputerHits": [{
           "Computer": "abc",
           "Hits": 9
       }, {
           "Computer": "contoso-cscoISE-syslg",
           "Hits": 66
       }]
   }];

var C = custom_parser(B);
document.getElementById("output").innerHTML=JSON.stringify(C);
&#13;
<div id = "output"></div>
&#13;
&#13;
&#13;