我試圖尋找一個JSON物件,并提取鍵/值對的'name'和'id'下面。我想提取'name'and 的所有實體'id':
{
"response": [
{
"additionalInfo": [],
"id": "b6549916-b8e1-4131-b0be-f4a3daee26fc",
"instanceTenantId": "5ffc97db91d68700c7ea827a",
"name": "Global",
"siteHierarchy": "b6549916-a8e1-4131-b0be-f4a3daee26fc",
"siteNameHierarchy": "Global"
},
{
"additionalInfo": [
{
"attributes": {
"addressInheritedFrom": "66284774-4ae4-42a1-b27c-68231c98d7db",
"type": "area"
},
"nameSpace": "Location"
}
],
"id": "4ffb292c-4cc8-444b-8978-61b97c6874db",
"instanceTenantId": "5ffc97db91d68700c7ea827a",
"name": "Peak Tester",
"parentId": "66a84774-4ae4-42a1-b27c-68231c98d7db",
"siteHierarchy": "b6549916-b8e1-4131-b0be-f4a3daee21fc/66a84774-4ae4-42a1-b27c-68231c98d7db/4ffb292c-4cc8-444b-8978-61b97c6874db",
"siteNameHierarchy": "Global/Template Site/Peak Tester"
}
]
}
我已經嘗試了幾件不起作用的事情。
for elements in site_info['response']:
for item in elements:
if item == 'name':
print(item)
這僅列印輸出'name'而不是值。我想要價值和鑰匙。
uj5u.com熱心網友回復:
只需當您擁有key并且需要 時value,您必須這樣做:
>>> dictionary['key']
'value'
在你的情況下:
if item == 'name':
print(item['name'])
無論如何,您可以通過if這種方式簡單地省略該陳述句:
for item in elements:
print(item['name'])
uj5u.com熱心網友回復:
我看到你已經有了答案,這很好。
data = { "response": [ {"name" : "fred"}, {"name" : "tom"}]} # data is a dictionary
arr = data['response'] # arr is a list of dictionaries
for i in arr:
print('name', i['name']) # lookup the name value from each sub-dictionary
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/418926.html
標籤:
