Страницы

Поиск по вопросам

четверг, 9 января 2020 г.

Как вытащить значение из словаря JSON?

#python #json


Пишу на Python. Из словаря в JSON нужно вытащить значение ключа "city". Кусок словаря
ниже.

{
  "query": {
    "count": 1,
    "created": "2018-07-15T13:21:02Z",
    "lang": "en-US",
    "results": {
      "channel": {
        "units": {
          "distance": "mi",
          "pressure": "in",
          "speed": "mph",
          "temperature": "F"
        },
        "title": "Yahoo! Weather - Nome, AK, US",
        "link": "http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-2460286/",
        "description": "Yahoo! Weather for Nome, AK, US",
        "language": "en-us",
        "lastBuildDate": "Sun, 15 Jul 2018 05:21 AM AKDT",
        "ttl": "60",
        "location": {
          "city": "Nome",
          "country": "United States",
          "region": " AK"
        },
        "wind": {
          "chill": "50",
          "direction": "270",
          "speed": "11"
        },
        "atmosphere": {
          "humidity": "90",
          "pressure": "1009.0",
          "rising": "0",
          "visibility": "14.9"
        },
        "astronomy": {
          "sunrise": "1:4 am",
          "sunset": "5:9 am"
        },
        "image": {
          "title": "Yahoo! Weather",
          "width": "142",
          "height": "18",
          "link": "http://weather.yahoo.com",
          "url": "http://l.yimg.com/a/i/brand/purplelogo//uh/us/news-wea.gif"
        },
        "item": {
          "title": "Conditions for Nome, AK, US at 03:00 AM AKDT",
          "lat": "64.499474",
          "long": "-165.405792",
          "link": "http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-2460286/",
          "pubDate": "Sun, 15 Jul 2018 03:00 AM AKDT",
          "condition": {
            "code": "26",
            "date": "Sun, 15 Jul 2018 03:00 AM AKDT",
            "temp": "52",
            "text": "Cloudy"
          },
          "forecast": [
            {
              "code": "11",
              "date": "15 Jul 2018",
              "day": "Sun",
              "high": "53",
              "low": "49",
              "text": "Showers"
            },


Значение ключа "count" вывести получается:

response = requests.get(url).json()
print(response["query"]["count"])


А вот то, что дальше не знаю как оформить, подскажите, пожалуйста.
    


Ответы

Ответ 1



Воспользуйтесь модулем dpath: In [193]: import dpath # pip install dpath In [194]: dpath.util.search(response, '**/city') Out[194]: {'query': {'results': {'channel': {'location': {'city': 'Nome'}}}}} In [199]: dpath.util.values(response, '**/city') Out[199]: ['Nome'] In [200]: dpath.util.get(response, '/query/results/channel/location/city') Out[200]: 'Nome' PS пример валидного JSON response... In [201]: url = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22munich%2C%20germany%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys' In [202]: import requests In [203]: response = requests.get(url).json() In [204]: dpath.util.get(response, '/query/results/channel/location/city') Out[204]: 'Munich' In [205]: dpath.util.values(response, '**/city') Out[205]: ['Munich'] In [206]: dpath.util.search(response, '**/city') Out[206]: {'query': {'results': {'channel': {'location': {'city': 'Munich'}}}}} In [207]: dpath.util.get(response, '/query/results/channel/location') Out[207]: {'city': 'Munich', 'country': 'Germany', 'region': ' BY'}

Комментариев нет:

Отправить комментарий