【问题标题】:Parsing Nested Objects in a Json using JS [duplicate]使用JS解析Json中的嵌套对象[重复]
【发布时间】:2013-02-25 11:28:11
【问题描述】:

我有一个这种格式的 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.xml 生成新的用户数组。例如:

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

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

【问题讨论】:

  • 请发布您的代码,我们或许可以为您提供帮助。

标签: javascript jquery json parsing loops


【解决方案1】:

我想你会做这样的事情:

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

【讨论】:

    【解决方案2】:

    大多数现代浏览器都支持原生 JSON.parse 方法。详情见这个问题Browser-native JSON support (window.JSON)

    【讨论】:

      猜你喜欢
      • 2016-12-23
      • 2019-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多