代码之家  ›  专栏  ›  技术社区  ›  SpaceCadet

使用openweathermap api解析字典(json)中的数据

  •  1
  • SpaceCadet  · 技术社区  · 7 年前

    import requests, pytemperature, json
    
    r = requests.get('http://samples.openweathermap.org/data/2.5/forecast?
    lat=35&lon=139&appid=b1b15e88fa797225412429c1c50c122a1')
    dict = r.json()
    
    for key, value in dict.items():
        if 'dt_txt' in str(key):
            print(key)
    

    这是上面链接中的JSON快照或完整内容。

        {
    "cod": "200",
    "message": 0.179,
    "cnt": 40,
    "list": [{
            "dt": 1509202800,
            "main": {
                "temp": 297.18,
                "temp_min": 291.573,
                "temp_max": 297.18,
                "pressure": 1027.02,
                "sea_level": 1029.75,
                "grnd_level": 1027.02,
                "humidity": 68,
                "temp_kf": 5.6
            },
            "weather": [{
                    "id": 500,
                    "main": "Rain",
                    "description": "light rain",
                    "icon": "10d"
                }
            ],
            "clouds": {
                "all": 88
            },
            "wind": {
                "speed": 1.61,
                "deg": 99.0033
            },
            "rain": {
                "3h": 0.09
            },
            "sys": {
                "pod": "d"
            },
            "dt_txt": "2017-10-28 15:00:00"
        }, {
            "dt": 1509213600,
            "main": {
                "temp": 297.32,
                "temp_min": 293.116,
                "temp_max": 297.32,
                "pressure": 1024.56,
                "sea_level": 1027.16,
                "grnd_level": 1024.56,
                "humidity": 76,
                "temp_kf": 4.2
            },
            "weather": [{
                    "id": 500,
                    "main": "Rain",
                    "description": "light rain",
                    "icon": "10d"
                }
            ],
            "clouds": {
                "all": 48
            },
            "wind": {
                "speed": 1.96,
                "deg": 173.002
            },
            "rain": {
                "3h": 0.41
            },
            "sys": {
                "pod": "d"
            },
            "dt_txt": "2017-10-28 18:00:00"
    

    旁注:最后,我试图打印日期、temp\u min、temp\u max、main和描述。我将把温度从开尔文转换成华氏度,然后用gmail每天发短信给我新的预测。提前感谢您的帮助!

    1 回复  |  直到 7 年前
        1
  •  3
  •   DRPK    7 年前

    您可以通过您的dict['your\u value']来设置所有dict键,请尝试以下操作:

    import requests, json
    
    r = requests.get('http://samples.openweathermap.org/data/2.5/forecast?lat=35&lon=139&appid=b1b15e88fa797225412429c1c50c122a1')
    dict = r.json()
    select_data = dict['list']
    
    for box in select_data:
    
        if 'dt_txt' in box:
            print(box['dt_txt'])
    
        else:
            print('not found')