PythonによるHTTPリクエストとJSONパーシング

Google Directions API を通じて Google Maps を動的に照会したいと考えています。例として、このリクエストでは、イリノイ州シカゴから、ミズーリ州ジョプリンとオクラホマシティの2つのウェイポイントを経由して、カリフォルニア州ロサンゼルスまでのルートを計算します。

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

JSON形式]1の結果が返ってきます。

これをPythonで行うにはどうしたらいいでしょうか?このようなリクエストを送り、結果を受け取り、それを解析したいのです。

ソリューション

私は、素晴らしいrequestsライブラリを使用することをお勧めします。

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レスポンスコンテンツ。http://docs.python-requests.org/en/latest/user/quickstart/#json-response-content

解説 (1)
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))
解説 (4)

requests ライブラリを使用して、抽出したいキーや値を見つけやすいように結果をプリティプリントし、ネストした 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']
解説 (2)