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.
The JSON data snippet:
{
"people": [
{
"person": {
"name": "joe",
"email": "[email protected]",
"groups": [
{
"name": "office",
"id": 23
},
{
"name": "mfg",
"id": 93
} ]
},
"person": {
"name": "bill",
"email": "[email protected]",
"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?
forloop onval["groups"]. Or is that not what you want?