【问题标题】:How to handle Json response and How Can I sperate value from this Json response in my terminal window如何处理 Json 响应以及如何在终端窗口中将值与此 Json 响应分开
【发布时间】:2021-08-02 10:02:20
【问题描述】:
`import requests
from requests.models import Response

api_key = "xxx"
city = "Houston"
Response = requests.get(
    f"https://api.openweathermap.org/data/2.5/weather?q={city},us&appid={api_key}")

full_info = (Response.json()["weather"])

print(full_info)`

输出:

{'coord': {'lon': -95.3633, 'lat': 29.7633}, 'weather': [{'id': 800, 'main': 'Clear', 'description': 'clear sky', 'icon': '01n'}], 'base': 'stations', 'main': {'temp': 299.96, 'feels_like': 302.81, 'temp_min': 298.12, 'temp_max': 301.26, 'pressure': 1015, 'humidity': 84}, 'visibility': 10000, 'wind': {'speed': 0.89, 'deg': 231, 
'gust': 4.02}, 'clouds': {'all': 1}, 'dt': 1627897632, 'sys': {'type': 2, 'id': 2006306, 'country': 'US', 'sunrise': 1627904498, 'sunset': 1627953218}, 'timezone': -18000, 'id': 4699066, 'name': 'Houston', 'cod': 200}

如果我使用 full_info = response.json()["weather"]

输出: [{'id': 800, 'main': 'Clear', 'description': 'clear sky', 'icon': '01n'}] 在检查了它的类型之后它的列表 但我无法访问特定的键值,例如 Main 或描述

如何实现不同变量中的所有值或仅访问我想要的值

如果我尝试使用索引打印

print(full_info[0])

输出保持不变

【问题讨论】:

    标签: python json api response


    【解决方案1】:

    full_info = Response.json() 然后

    print(full_info['weather'][0]['id'])

    【讨论】:

    • print(full_info[0][1]) KeyError: 1 it give key error
    • 执行full_info = Response.json() 然后print(full_info['weather'][0]['id']) 它应该可以工作
    • 它工作 Binit 谢谢你能支持这个问题吗?
    猜你喜欢
    • 2018-03-11
    • 1970-01-01
    • 2014-09-28
    • 2011-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多