使用JS在Json中解析嵌套对象 [英] Parsing Nested Objects in a Json using JS

查看:967
本文介绍了使用JS在Json中解析嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种格式的Json:

I have a Json in this format:

{"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生成新的用户数组。例如:

How can I generate new arrays of users from the Json. For example:

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

我已尝试嵌套 for 循环,我试过 for..in 循环也是如此。我确信我犯了一个错误。我有什么想法可以过滤/解析这些嵌套的json对象所需的信息吗?

I have tried nested for loop and I have tried for..in loop too. I am sure I am making a mistake. Any ideas how I can filter/parse the required information for such nested json objects?

推荐答案

我想你会做类似的事情:

I would imagine you would do something like:

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
          }
       }
    }
  }
}

这篇关于使用JS在Json中解析嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆