1

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?

2
  • Use a for loop on val["groups"]. Or is that not what you want? Commented Apr 5, 2016 at 15:35
  • Instead of try/except, you can say val.get("groups", []) and the iterate over that. If that person doesn't have groups it will return an empty list. Commented Apr 5, 2016 at 15:45

1 Answer 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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! The second example you show is just what I needed. whew!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.