我有这个json文件:
{
"id": "manager",
"children": [
{
"id": "user1",
"children": [],
"data": {
"name": "john",
"age": "55",
"lastname": "smith",
}
},
{
"id": "user2",
"children": [],
"data": {
"name": "mark",
"age": "56",
"lastname": "guri",
}
},
{
"id": "user3",
"children": [],
"data": {
"name": "alex",
"age": "57",
"lastname": "muller",
}
}
],
"data": {
"name": "sukri",
"age": "24",
"lastname": "adam"
}
}
我正在尝试为每个儿童下的这些信息分配一个变量。这样我以后就可以访问它们了
挑战在于遍历manager下的所有子节点。
结果应该是这样的:
children1{id=user1, name=john, age="55"}
children2{…}
children3{…}
它应该到列表的末尾并捕获所有信息。
请让我知道如何实现这一点。我有以下不起作用的代码:
with open('data.json') as json_file:
data = json.load(json_file)
print ("id:", data['manager'])
print ("")
for children in data['manager']:
print("name:", children['name'])
print("age:", children['age'])
print("lastname:", children['lastname'])
print("")
您可以像这样创建一个包含每个子元素数据的列表。
import json
with open('data.json') as json_file:
data = json.load(json_file)
children = [child['data'] for child in data['children']]
print(children)
[{'name': 'john', 'age': '55', 'lastname': 'smith'}, {'name': 'mark', 'age': '56', 'lastname': 'guri'}, {'name': 'alex', 'age': '57', 'lastname': 'muller'}]
或者,您可以使用this创建子元素的字典。
children_dict = {f'user{id+1}': child['data'] for id, child in enumerate(data['children'])}
print(children_dict['user1'])
{'name': 'john', 'age': '55', 'lastname': 'smith'}