Как разобрать данные из JSON запроса? - PullRequest
1 голос
/ 17 апреля 2020

Я пытаюсь проанализировать определенные c части ответа JSON с помощью API OpenWeatherMap.org и Python на Raspberry Pi 3. Я могу получить полный ответ, используя этот скрипт:

import requests
import json

settings = {
    'api_key':'my API key',
    'zip_code':'80550',
    'country_code':'us',
    'temp_unit':'imperial'} #unit can be metric, imperial, or kelvin

BASE_URL = "http://api.openweathermap.org/data/2.5/weather?appid={0}&zip={1},{2$

final_url = BASE_URL.format(settings["api_key"],settings["zip_code"],settings["$
weather_data = requests.get(final_url).json()

print(weather_data)

На этом этапе я получаю следующее:

{'coord': {'lon': -104.9, 'lat': 40.48}, 'weather': [{'id': 601, 'main': 'Snow', 'description': 'snow', 'icon': '13d'}, {'id': 701, 'main': 'Mist', 'description': 'mist', 'icon': '50d'}], 'base': 'stations', 'main': {'temp': 26.31, 'feels_like': 13.14, 'temp_min': 18, 'temp_max': 32, 'pressure': 1022, 'humidity': 86}, 'visibility': 3219, 'wind': {'speed': 14.99, 'deg': 30}, 'snow': {'1h': 0.64}, 'clouds': {'all': 100}, 'dt': 1587077009, 'sys': {'type': 1, 'id': 4120, 'country': 'US', 'sunrise': 1587039511, 'sunset': 1587087572}, 'timezone': -21600, 'id': 0, 'name': 'Windsor', 'cod': 200}

Я хотел бы проанализировать такие данные, как «описание» в разделе «погода» ответа, и сохранить их в переменная, но я продолжаю сталкиваться с различными типами ошибок. Кажется, это должен быть очень простой процесс, но я изо всех сил пытаюсь найти то, что должно быть очевидным ответом.

Ответы [ 2 ]

2 голосов
/ 17 апреля 2020

Ваш weather_data словарь. description Один из ключей словаря указывает на список словарей. Вам нужно посмотреть на каждый предмет в этом списке и вытащить description. Самый простой способ - это понять список:

descriptions = [item['description'] for item in weather_data['weather']]
# ['snow', 'mist']

Это даст вам новый список только с описаниями.

2 голосов
/ 17 апреля 2020
obj = {'coord': {'lon': -104.9, 'lat': 40.48}, 'weather': [{'id': 601, 'main': 'Snow', 'description': 'snow', 'icon': '13d'}, {'id': 701, 'main': 'Mist', 'description': 'mist', 'icon': '50d'}], 'base': 'stations', 'main': {'temp': 26.31, 'feels_like': 13.14, 'temp_min': 18, 'temp_max': 32, 'pressure': 1022, 'humidity': 86}, 'visibility': 3219, 'wind': {'speed': 14.99, 'deg': 30}, 'snow': {'1h': 0.64}, 'clouds': {'all': 100}, 'dt': 1587077009, 'sys': {'type': 1, 'id': 4120, 'country': 'US', 'sunrise': 1587039511, 'sunset': 1587087572}, 'timezone': -21600, 'id': 0, 'name': 'Windsor', 'cod': 200}

for weather in obj['weather']:
    print(weather['description'])

отпечатки

snow
mist
...