Adam vonNieda
Adam vonNieda

Reputation: 1745

Parsing JSON with Python, trouble with an array of arrays

I've got a JSON structure that looks like the following

{
  "PersonInformation": {
    "PhysicalStatus": "",
    "OpenDetainers": [],
    "StartDate": "",
    "FacilityLog": [],
    "CustStatus": "",
    "EndDate": ""
  },
  "IdentityList": [
    {
      "CreationDate": "01/01/1999",
      "PersonNames": [
        {
          "Suffix": "",
          "FirstName": "Johnny",
          "LastName": "Appleseed",
          "MiddleName": ""
        },
        {
          "Suffix": "",
          "FirstName": "Foo",
          "LastName": "Bar",
          "MiddleName": ""
        }
      ],
      "PlaceOfBirthList": [
        {
          "City": "Boston",
          "State": "MA",
          "CountryCode": ""
        }
      ]
    }
  ]
}

I can parse the outer array like so, but I'm having trouble figuring out how to loop through one of the child arrays, like "PersonNames"

So I can do this

myjson = json.loads(json_data)
print myjson['PersonInformation']['PhysicalStatus']
for identity_list in myjson['IdentityList']:
    print identity_list['CreationDate']

Which returns

OK
01/01/1999 

as expected, but I don't know how to take it to the next level to traverse into and loop through "PersonNames"

Thanks for the assistance

Upvotes: 1

Views: 167

Answers (1)

blhsing
blhsing

Reputation: 106568

You can iterate through the sub-list under the PersonNames key like this:

for identity in myjson['IdentityList']:
    for person in identity['PersonNames']:
        print person['FirstName'], person['LastName']

Upvotes: 2

Related Questions