简体   繁体   中英

Iterating json array in javascript

after looking through a lot of similar questions on SO, I still can't iterate my json structure. How can I reach the value (key) of my inner array?

var data = {"User1":{"Service1":2,"Service2":1},"User2":{"Service3":1}}

for(var user in data) {
    document.write(user + ': ')

    for(var service in data[user]){
        document.write(service + ': ' + user[service])
    }
    document.write("<br />")
}

This prints:

User1: Service1: undefined Service2: undefined

User2: Service3: undefined

And I'd like it to print

User1: Service1: 2 Service2: 1

User2: Service3: 1

Is javascript enough or do I need jQuery? Thanks in advance!

var data = {
  User1: {
    Service1: 2,
    Service2: 1
  },
  User2: {
    Service3: 1
  }
};
for (var user in data) {
  console.log("User: " + user);
  for (var service in data[user]) {
    console.log("\tService: " + service + "; value: " + data[user][service]);
  }
}

Replace console.log with document.write or whatever.

document.write(service + ': ' + data[user][service])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM