Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to search 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. I would like to extract all instances of the '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"
    }
]

}

I have tried several things that are not working.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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. I would like the value as well as the key.

>Solution :

Simply when you have the key and you need the value, you have to do this:

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

In your case:

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

Anyway you can simply omitt the if statement this way:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading