[python] 파이썬에서 HTTP 요청과 JSON 파싱

Google Directions API를 통해 Google지도를 동적으로 쿼리하고 싶습니다. 예를 들어,이 요청은 MO, Joplin, Oklahoma City, OK의 두 웨이 포인트를 통해 일리노이 주 시카고에서 로스 앤젤레스, 캘리포니아까지의 경로를 계산합니다.

http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false

JSON 형식으로 결과 반환 합니다 .

파이썬에서 어떻게 할 수 있습니까? 그런 요청을 보내고 결과를 받아 파싱하고 싶습니다.



답변

멋진 요청 라이브러리를 사용하는 것이 좋습니다 .

import requests

url = 'http://maps.googleapis.com/maps/api/directions/json'

params = dict(
    origin='Chicago,IL',
    destination='Los+Angeles,CA',
    waypoints='Joplin,MO|Oklahoma+City,OK',
    sensor='false'
)

resp = requests.get(url=url, params=params)
data = resp.json() # Check the JSON Response Content documentation below

JSON 응답 컨텐츠 : https://requests.readthedocs.io/en/master/user/quickstart/#json-response-content


답변

requests파이썬 모듈을 담당 모두 JSON 데이터를 검색하고 인해 내장 된 JSON 디코더이를 디코딩. 다음은 모듈 설명서 에서 가져온 예입니다 .

>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...

따라서 JSON 디코딩에 별도의 모듈을 사용할 필요가 없습니다.


답변

requests내장 .json()방법이 있습니다

import requests
requests.get(url).json()


답변

import urllib
import json

url = 'http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false'
result = json.load(urllib.urlopen(url))


답변

요청 라이브러리를 사용하고 결과를 인쇄하여 추출하려는 키 / 값을 더 잘 찾은 다음 중첩 된 for 루프를 사용하여 데이터를 구문 분석하십시오. 이 예에서는 단계별 운전 방향을 추출합니다.

import json, requests, pprint

url = 'http://maps.googleapis.com/maps/api/directions/json?'

params = dict(
    origin='Chicago,IL',
    destination='Los+Angeles,CA',
    waypoints='Joplin,MO|Oklahoma+City,OK',
    sensor='false'
)


data = requests.get(url=url, params=params)
binary = data.content
output = json.loads(binary)

# test to see if the request was valid
#print output['status']

# output all of the results
#pprint.pprint(output)

# step-by-step directions
for route in output['routes']:
        for leg in route['legs']:
            for step in leg['steps']:
                print step['html_instructions']


답변

이 시도:

import requests
import json

# Goole Maps API.
link = 'http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false'

# Request data from link as 'str'
data = requests.get(link).text

# convert 'str' to Json
data = json.loads(data)

# Now you can access Json 
for i in data['routes'][0]['legs'][0]['steps']:
    lattitude = i['start_location']['lat']
    longitude = i['start_location']['lng']
    print('{}, {}'.format(lattitude, longitude))


답변

또한 콘솔의 예쁜 Json의 경우 :

 json.dumps(response.json(), indent=2)

들여 쓰기로 덤프를 사용할 수 있습니다. ( json을 가져 오십시오 )