0

I have a Json in this format:

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

Sample:

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

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

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

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?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Hitesh
  • 2,045
  • 2
  • 14
  • 9

2 Answers2

3

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
          }
       }
    }
  }
}
paulslater19
  • 5,869
  • 1
  • 28
  • 25
0

Most modern browsers support the native JSON.parse method. See this question for details Browser-native JSON support (window.JSON)

Community
  • 1
  • 1
Jason
  • 15,915
  • 3
  • 48
  • 72