简体   繁体   English

Python JSON - 搜索 JSON Z497031794414A552435F9015B1C 对并提取密钥对

[英]Python JSON - Search the JSON Object and extract the Key/Value pair

I'm trying to search a JSON Object and extract the Key/Value pairs for 'name' and 'id' below.我正在尝试搜索 JSON Object 并提取下面的“名称”和“ID”的键/值 I would like to extract all instances of the 'name' and 'id':我想提取'name'和'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"
    }
]

} }

I have tried several things that are not working.我已经尝试了几件不起作用的事情。 I'm a python beginner so I appreciate any help.我是 python 初学者,所以我很感激任何帮助。

for elements in site_info['response']:
for item in elements:
    if item == 'name':
        print(item)
        

This only prints the output of 'name' and not the value.这仅打印“名称”的 output 而不是值。 I would like the value as well as the key.我想要价值和钥匙。

Simply when you have the key and you need the value , you have to do this:只需当您拥有key并且需要value时,您就必须这样做:

>>> dictionary['key']
'value'

In your case:在你的情况下:

if item == 'name':
    print(item['name'])

Anyway you can simply omitt the if statement this way:无论如何,您可以通过这种方式简单地省略if语句:

for item in elements:
    print(item['name'])

I see you already have your answer, which is great.我看到你已经有了答案,这很好。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM