How do I loop through a JSON file with multiple sub-keys in Python?

Viewed 262

I have a json file:-

{
    "group": "avengers",
    "members": [
      {
        "name": "Dr.Strange",
        "id": 456409,
        "type": "magic",
        "relatives": ["wang", "the ancient one"]
      },
      {
        "name": "Iron man",
        "id": 381001,
        "type": "technology",
        "relatives": ["pepper pots", "james rhodes"]
      }
    ]
}

I want the output as:-

Members from avengers group:-

Name ID Type Relatives
Dr. Strange 456409 magic wang
Dr. Strange 456409 magic the ancient one
Iron man 381001 technology pepper pots
Iron man 381001 technology james rhodes

I want to get all relatives seperately. I know how to get the name, id and types because they have only 1 value.

My code:-

import json

f = open('1.json', 'r')
content = json.load(f)

for i in content['members']:
  print(i['name'], end=' ')
  print(i['id'], end=' ')
  print(i['relatives'])
  print()

Output of my code:-

Dr.Strange 456409 ['wang', 'the ancient one'] 

Iron man 381001 ['pepper pots', 'james rhodes']

But I want seperate relatives not in a list. So for each relative retype the name like in the table I put above.

I know that I can use i['relatives'][0] but what if I don't know the number of relatives? Maybe a for loop can help?

Thank you!

3 Answers

Yes, for loops work. Try:

for mem in content['members']:
    for rel in mem['relatives']: # i.e., for each member, loop over relatives
        print(f"{mem['name']:10} {mem['id']:6} {mem['type']:10} {rel:20}")

Output:

Dr.Strange 456409 magic      wang
Dr.Strange 456409 magic      the ancient one
Iron man   381001 technology pepper pots
Iron man   381001 technology james rhodes

You could do for example like this:

import json

f = open('1.json', 'r')
content = json.load(f)

for superhero in content .get('members'):

    if type(superhero.get('relatives')) == list:
        values = ' ,'.join([value for value in superhero.get('relatives')])
            
    print(superhero.get('id'), superhero.get('name'), 'Relatives: ', values)

you can always check the length of list and make a loop to iterate over that length.

for j in range(0,len(i)):
    i['relatives'][j]

I think it might help.

Related