解析嵌套对象以JSON使用JS
问题描述:
我有一个JSON格式如下:解析嵌套对象以JSON使用JS
{"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对象所需的信息?
答
我可以想象你会做这样的事情:
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
}
}
}
}
}
+0
谢谢,它工作 – Hitesh 2013-02-25 19:55:45
请发表您的代码,我们也许能帮助你用它。 – 2013-02-25 11:29:51