IT이야기

Python에서 HTTP 요청 및 JSON 구문 분석

cyworld 2022. 3. 26. 15:42
반응형

Python에서 HTTP 요청 및 JSON 구문 분석

구글 디렉션 API를 통해 동적으로 구글 맵을 조회하고 싶다.예를 들어, 이 요청은 조플린, MO, 오클라호마 시티의 두 가지 경유지를 통해 시카고, IL에서 로스앤젤레스, CA로 가는 경로를 계산한다.

http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|오클라호마+시티,OK&센서=거짓말

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

파이톤 모듈은 내장된 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))

요청 라이브러리를 사용하여 추출할 키/값을 더 잘 찾을 수 있도록 결과를 예쁘게 인쇄한 다음 루프의 내포된 값을 사용하여 데이터를 구문 분석하십시오.이 예에서 나는 단계별 운전 방향을 추출한다.

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))

정의의import requests그리고 에서 사용하다json()방법:

source = requests.get("url").json()
print(source)

또는 다음을 사용할 수 있다.

import json,urllib.request
data = urllib.request.urlopen("url").read()
output = json.loads(data)
print (output)

콘솔에 있는 예쁜 Json에게도:

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

들여쓰기가 있는 덤프 사용 가능(json 가져오기)

참조URL: https://stackoverflow.com/questions/6386308/http-requests-and-json-parsing-in-python

반응형