【问题标题】:How to display specific parts of json?如何显示json的特定部分?
【发布时间】:2016-09-20 20:08:38
【问题描述】:

有人可以帮我解决这个 python api 调用程序吗?

import json
from pprint import pprint
import requests
weather = requests.get('http://api.openweathermap.org/data/2.5/weather?    
q=London&APPID=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
pprint(weather.json())

wjson = weather.read()
wjdata = json.load(weather)
print (wjdata['temp_max'])

因此,通过这段代码,我试图从天气 api 获取信息,它会正确打印它,但是当我只想选择某些值时,我会收到此错误。

Traceback (most recent call last):
  File "gawwad.py", line 7, in <module>
    wjson = weather.read()
AttributeError: 'Response' object has no attribute 'read'

【问题讨论】:

    标签: python json api


    【解决方案1】:

    .json()是内置于requests的JSON解码器,无需单独解析JSON:

    import requests
    
    weather = requests.get('http://api.openweathermap.org/data/2.5/weather?q=London&APPID=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
    wjdata = weather.json()
    print (wjdata['temp_max'])
    

    【讨论】:

      【解决方案2】:

      alecxe 使用 json 库是正确的,如果您想了解有关在 json 对象中引用特定值的更多信息,请查看 pythons 字典数据类型。这就是 json 本质上将它们转换成的内容。

      https://docs.python.org/3/tutorial/datastructures.html#dictionaries

      上面的链接会告诉你如何使用它们!!字典是“键值”数据结构,其中键是唯一的,不能是可散列的,值是任何类型。

      python 字典快速示例:

      dict = {'keyA' : 'valueA', 'keyB': 'valueB'}
      # To reference a value, use the key!
      print(dict['keyA'])
      # To add something
      dict['keyC'] = 'valueC'
      # now my dictionary looks like this
      dict = {'keyA' : 'valueA', 'keyB': 'valueB', 'KeyC' : 'valueC'}
      

      打印语句将输出'valueA'

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-19
        • 2016-09-09
        相关资源
        最近更新 更多