A
A
Alexsey2022-04-17 14:58:27
Python
Alexsey, 2022-04-17 14:58:27

How to parse JSON results by condition?

Good afternoon
There is such a JSON and a script in Python. Which displays a list of companies on the screen.
How, for example, to display regions from Company1 or another by condition.

{
    "data": [
        {
            "id": 1,
            "attributes": {
                "name": "Company1",
                "regions": {
                    "data": [
                        {
                            "id": 1,
                            "attributes": {
                                "name": "Ленинградская область",
                            }
                        },
                        {
                            "id": 2,
                            "attributes": {
                                "name": "Московская область",
                            }
                        },
                        {
                            "id": 3,
                            "attributes": {
                                "name": "Волгоградская область",
                            }
                        },
                    ]
                }
            }
        },
        {
            "id": 2,
            "attributes": {
                "name": "Company2",
                "regions": {
                    "data": [
                        {
                            "id": 1,
                            "attributes": {
                                "name": "Ленинградская область",
                            }
                        },
                        {
                            "id": 2,
                            "attributes": {
                                "name": "Московская область",
                            }
                        }
                    ]
                }
            }
        },
    ],
}

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'])

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Nesterov, 2022-04-17
@Ernesto

for data in res_content['data']:
  attributes = data['attributes']

  regions = attributes['regions']['data']
  name = attributes['name']
  print(name)
  for region in regions:
    print('--',region['attributes']['name'])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question