'How to parse JSON results by condition?

There is JSON and a Python script. Which displays a list of Companies on the screen. How to display all Regions for Company[id] ?

{
    "data": [
        {
            "id": 1,
            "attributes": {
                "name": "Company1",
                "regions": {
                    "data": [
                        {
                            "id": 1,
                            "attributes": {
                                "name": "Region 1",
                            }
                        },
                        {
                            "id": 2,
                            "attributes": {
                                "name": "Region 2",
                            }
                        },
                    ]
                }
            }
        },
        {
            "id": 2,
            "attributes": {
                "name": "Company2",
                "regions": {
                    "data": [
                        {
                            "id": 1,
                            "attributes": {
                                "name": "Region 1",
                            }
                        },
                        {
                            "id": 2,
                            "attributes": {
                                "name": "Region 2",
                            }
                        }
                    ]
                }
            }
        },
    ],
}

Script for all companies.

import os
import json
import requests

BASE_URL = 'localhost'

res = requests.get(BASE_URL)
res_content = json.loads(res.content)

for holding in res_content['data']:
    print(holding['id'], holding['attributes']['name'])

How to do the same for displaying the Region for Company[id] ? Example: Display all Regions for Company 1



Solution 1:[1]

Iterate through a list of dictionaries, looking for a dictionary with the key 'name' that has the value 'Company1'. Once it finds that dictionary, it iterates through the list of dictionaries stored under the key 'regions' and prints the value of the key 'name' for each dictionary in that list.

You can try this:

for company in res_content['data']:
    if company['attributes']['name'] == 'Company1':
        for region in company['attributes']['regions']['data']:
            print(region['attributes']['name'])

Solution 2:[2]

You just need to delve further down into the res_content object:

for holding in res_content['data']:
    print(holding['id'], holding['attributes']['name'])
    data = holding['attributes']['regions']['data']
    for d in data:
        print('   ', d['attributes']['name'])

Output:

1 Company1
    Region 1
    Region 2
2 Company2
    Region 1
    Region 2

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Omar Ashraf
Solution 2 quamrana