HTTP requests and JSON parsing in Python

HTTP requests and JSON parsing in Python

I recommend using the awesome requests library:

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 Response Content: https://requests.readthedocs.io/en/master/user/quickstart/#json-response-content

The requests Python module takes care of both retrieving JSON data and decoding it, due to its builtin JSON decoder. Here is an example taken from the modules documentation:

>>> import requests
>>> r = requests.get(https://github.com/timeline.json)
>>> r.json()
[{urepository: {uopen_issues: 0, uurl: https://github.com/...

So there is no use of having to use some separate module for decoding JSON.

HTTP requests and JSON parsing in Python

requests has built-in .json() method

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

Leave a Reply

Your email address will not be published. Required fields are marked *