如何显示json的特定部分?

时间:2016-09-20 20:08:39

标签: python json api

有人可以帮我解决这个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'

2 个答案:

答案 0 :(得分:5)

.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'])

答案 1 :(得分:0)

alecxe使用json库是正确的,如果你想了解更多关于引用json对象中特定值的信息,请查看pythons Dictionary数据类型。这就是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'}

print语句将输出'valueA'