Ernesto
@Ernesto
Junior

Как парсить результаты JSON по условию?

Добрый день
Есть такой JSON и скрипт на Python. Который выводит список компаний на экран.
Как например вывести регионы у Компании1 или другой по условию.

{
    "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'])
  • Вопрос задан
  • 108 просмотров
Решения вопроса 1
AlexNest
@AlexNest Куратор тега Python
Работаю с Python/Django
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'])
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы