使用JS在Json中解析嵌套对象

时间:2013-02-25 11:28:11

标签: javascript jquery json parsing loops

我有这种格式的Json:

{"year":{"month1":{"date1":{"device1":{"users":6}}}}

样品:

{"2013":{"2":{"5":{"GT-N7000":{"users":1}},"6":{"GT-N7000":{"users":9},"HTC Sensation Z710a":{"users":1}},"7":{"GT-N7000":{"users":15},"HTC Sensation Z710a":{"users":2},"M903":{"users":1}}}}}

如何从Json生成新的用户数组。例如:

GT-N7000 = [1, 9, 15]
M903 = [1]

我尝试过嵌套for循环,我也尝试过for..in循环。我确信我犯了一个错误。有关如何过滤/解析此类嵌套json对象所需信息的任何想法吗?

2 个答案:

答案 0 :(得分:3)

我想你会做类似的事情:

var json = {"2013":{"2":{"5":{"GT-N7000":{"users":1}},"6":{"GT-N7000":{"users":9},"HTC Sensation Z710a":{"users":1}},"7":{"GT-N7000":{"users":15},"HTC Sensation Z710a":{"users":2},"M903":{"users":1}}}}}; 

var result = {}, year, month, date, item;
for (year in json) {
  for(month in json[year]) {
    for(date in json[year][month]) {
       for(item in json[year][month][date]) {
          if(item in result) {
              result[item].push(json[year][month][date][item].users)  // this bit might need editing?
          } else {
              result[item] = [json[year][month][date][item].users] // this be also might need editing
          }
       }
    }
  }
}

答案 1 :(得分:0)

大多数现代浏览器都支持本机JSON.parse方法。有关详细信息,请参阅此问题Browser-native JSON support (window.JSON)