2013-02-25 47 views
0

我有一個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對象所需的信息?

+3

請發表您的代碼,我們也許能幫助你用它。 – 2013-02-25 11:29:51

回答

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

謝謝,它工作 – Hitesh 2013-02-25 19:55:45