Home > Software engineering >  How can I get all parents element from this json by python?
How can I get all parents element from this json by python?

Time:10-16

test.json:

{
    "Peter": {"parents" : ["David","Susan"]},
    "Mark": {"parents" : ["Joseph","Barbara"]},
    "Eve": {"parents" : ["Mohamed","Sarah"]}
    }

test.py:

import json

f = open('test.json',)
data = json.load(f)
for element in data:
    print(element)
f.close()

When I run this command, the output is: Peter Mark Eve

My question would be how can I get back this result? David Susan Joseph Barbara Mohamed Sarah

CodePudding user response:

Instead of printing the element, print the parent information within each element:

import json

f = open('test.json',)
data = json.load(f)
for element in data:
    print(data[element]["parents"])
f.close()

CodePudding user response:

import json

with open('test.json', 'r') as f:
    data = f.read()

data = json.loads(data)

# With values()
for v in data.values():
    print(v['parents'])

# Or the same with list comprehension 
[v['parents'] for v in data.values()]

# With keys
for k in data:
    print(data[k]['parents'])

# Or the same with list comprehension 
[data[k]['parents'] for k in data]
  • Related