我正在处理多个JSON对象,这些对象将转换为嵌套字典,在其中提取最后一个字典(如“数据”部分所示)。我想将“标签”的所有值提取到列表中。在尝试执行此操作时,我得到的是输出,然后是错误。
代码:
import json
with open('console_data.json', 'r') as console_data:
parsed_data = console_data.read()
nodes = json.loads(parsed_data)
last_node = nodes[-1] # extract last dictionary
print("\n\n\n")
for item in last_node:
tags = last_node[item].get("Tags", {})
try:
print(tags)
except AttributeError:
pass
数据:
{
"Node": {
"ID": "1a2b78dc-078d-cfe2-6c55-189aa2c67d29",
"Node": "NAVIAPP05",
"Address": "10.2.2.5",
"Datacenter": "naviprod",
"TaggedAddresses": {
"lan": "10.2.2.5",
"wan": "10.2.2.5"
},
"Meta": {
"consul-network-segment": ""
},
"CreateIndex": 5171424,
"ModifyIndex": 5453151
},
"Service": {
"ID": "sim-work102235-10185",
"Service": "sim",
"Tags": [
"fc216ed1-ef55-4064-b25d-de37ac612984",
"2a82837f-1867-4b59-ab21-72331b75f4c2",
"732b3fc1-687b-42ac-b71f-d755fe90de04",
"d85d8902-8c36-4591-8f39-b4d8528301ce",
"d5d695a6-710f-4edc-ae03-47ee034137a4",
"62002f4a-4029-4f4f-a9d0-6b0fc2f34951",
"459cc8e3-fc44-43ce-9d7f-dfa3fe92665e"
],
"Address": "10.2.2.35",
"Meta": {
"apiContext": "/sim/sim.do",
"defaultContext": "/sim",
"workflowContext": "/sim/services",
"zspContext": "/sim/services",
"zspProductURL": "https://sim.abcde.com/sim/"
},
"Port": 10185,
"EnableTagOverride": false,
"CreateIndex": 7327367,
"ModifyIndex": 7327367
},
"Checks": [
{
"Node": "NAVIAPP05",
"CheckID": "serfHealth",
"Name": "Serf Health Status",
"Status": "passing",
"Notes": "",
"Output": "Agent alive and reachable",
"ServiceID": "",
"ServiceName": "",
"ServiceTags": [],
"Definition": {},
"CreateIndex": 5171424,
"ModifyIndex": 5171424
}
]
}
输出:
{}
['fc216ed1-ef55-4064-b25d-de37ac612984', '2a82837f-1867-4b59-ab21-72331b75f4c2', '732b3fc1-687b-42ac-b71f-d755fe90de04', 'd85d8902-8c36-4591-8f39-b4d8528301ce', 'd5d695a6-710f-4edc-ae03-47ee034137a4', '62002f4a-4029-4f4f-a9d0-6b0fc2f34951', '459cc8e3-fc44-43ce-9d7f-dfa3fe92665e']
Traceback (most recent call last):
File "so_parse_json.py", line 12, in <module>
tags = last_dict[item].get("Tags", {})
AttributeError: 'list' object has no attribute 'get'
预期输出:
['fc216ed1-ef55-4064-b25d-de37ac612984', '2a82837f-1867-4b59-ab21-72331b75f4c2', '732b3fc1-687b-42ac-b71f-d755fe90de04', 'd85d8902-8c36-4591-8f39-b4d8528301ce', 'd5d695a6-710f-4edc-ae03-47ee034137a4', '62002f4a-4029-4f4f-a9d0-6b0fc2f34951', '459cc8e3-fc44-43ce-9d7f-dfa3fe92665e']
答案 0 :(得分:1)
我不知道您的console_data.json
中有什么。该代码适用于以上Data
。
import json
with open('Data.json','r') as f:
data = f.read()
nodes = json.loads(data)
tags = nodes['Service']['Tags']
print(tags)
答案 1 :(得分:1)
假设您随附的数据来自last_node
,为什么不使用:
last_node['Service']['Tags']
这将输出:
['fc216ed1-ef55-4064-b25d-de37ac612984',
'2a82837f-1867-4b59-ab21-72331b75f4c2',
'732b3fc1-687b-42ac-b71f-d755fe90de04',
'd85d8902-8c36-4591-8f39-b4d8528301ce',
'd5d695a6-710f-4edc-ae03-47ee034137a4',
'62002f4a-4029-4f4f-a9d0-6b0fc2f34951',
'459cc8e3-fc44-43ce-9d7f-dfa3fe92665e']