2016-09-20 2 views
1

누군가가이 python API 호출 프로그램을 도와 줄 수 있습니까? json의 특정 부분을 표시하는 방법은 무엇입니까?

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' 

답변

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

alecxe에서, JSON 라이브러리를 사용으로 정확 json 객체, 비석 사전 데이터 유형을 살펴보십시오. 그것이 json이 본질적으로 그들을 변환시키는 것입니다.

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

링크는 위의 방법을 사용하는 방법을 보여줍니다! 사전은 키가 고유하며 해시 가능하지 않아야하는 '키 - 값'데이터 구조이며 값은 모든 유형입니다.

파이썬 사전 빠른 예 :

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'

관련 문제