New to python here. I'm trying to iterate over all the JSON "group" objects for each person but having some difficulty. This is only a partial list (not all users have groups) so I need to use the try/catch block so users without a list of groups don't cause early termination.
这里是python的新手。我试图为每个人迭代所有JSON“组”对象,但有一些困难。这只是一个部分列表(并非所有用户都有组)所以我需要使用try / catch块,因此没有组列表的用户不会导致提前终止。
The JSON data snippet:
JSON数据片段:
{
"people": [
{
"person": {
"name": "joe",
"email": "joe@foo.net",
"groups": [
{
"name": "office",
"id": 23
},
{
"name": "mfg",
"id": 93
} ]
},
"person": {
"name": "bill",
"email": "bill@foo.net",
"groups": [
{
"name": "acctg",
"id": 133
},
{
"name": "mgr",
"id": 207
} ]
}
}
]
}
This is my code so far:
到目前为止这是我的代码:
jdata = json.loads...
for person in jdata['people']:
for key, val in person.iteritems():
print "key ", key , " is ", val
print val["name"]
print val["email"]
try:
for gkey, gval in val["groups"][0].iteritems():
print "gval: " + gval
except:
foo=1
Notice I can print out a list of the 0th item in the group list by doing the for gkey...val["groups"][0].iteritems()
but what I really want is iterate over all the group
lists of each person
entry (some people belong to two groups, others 10 or more) so there is no fixed length. How can I do this?
注意我可以通过执行for gkey ... val [“groups”] [0] .iteritems()打印出组列表中第0项的列表,但我真正想要的是遍历每个组的所有组列表人进入(有些人属于两组,有些人属于10组或更多)所以没有固定的长度。我怎样才能做到这一点?
1 个解决方案
#1
1
Is that what you want? :
那是你要的吗? :
>>> for group in j['people'][0]['person']['groups']:
for k,v in group.items():
print(k,v)
name acctg
id 133
name mgr
id 207
Or more generally:
或者更一般地说:
>>> for person in j['people']:
for group in person['person']['groups']:
print('Name : {} --- ID: {}'.format(group['name'], group['id']))
Name : acctg --- ID: 133
Name : mgr --- ID: 207
#1
1
Is that what you want? :
那是你要的吗? :
>>> for group in j['people'][0]['person']['groups']:
for k,v in group.items():
print(k,v)
name acctg
id 133
name mgr
id 207
Or more generally:
或者更一般地说:
>>> for person in j['people']:
for group in person['person']['groups']:
print('Name : {} --- ID: {}'.format(group['name'], group['id']))
Name : acctg --- ID: 133
Name : mgr --- ID: 207