import requests
r = requests.get('http://httpbin.org/get');
r.text
returns:
u'{\n "url": "http://httpbin.org/get",\n "headers": {\n "Host": "httpbin.org",\n "Accept-Encoding": "gzip, deflate, compress",\n "Connection": "close",\n "Accept": "*/*",\n "User-Agent": "python-requests/2.2.1 CPython/2.7.5 Windows/7",\n "X-Request-Id": "db302999-d07f-4dd6-8c1e-14db45d39fb0"\n },\n "origin": "61.228.172.190",\n "args": {}\n}'
How can get the origin
and headers/Host
values?
To read a JSON response there is a widely used library called urllib in python. This library helps to open the URL and read the JSON response from the web. To use this library in python and fetch JSON response we have to import the json and urllib in our code, The json. loads() method returns JSON object.
So first thing you need to import the 'json' module into the file. Then create a simple json object string in python and assign it to a variable. Now we will use the loads() function from 'json' module to load the json data from the variable. We store the json data as a string in python with quotes notation.
Instead of the JSON loads method, which reads JSON strings, the method used to read JSON data in files is load(). The load() method takes up a file object and returns the JSON data parsed into a Python object. To get the file object from a file path, Python's open() function can be used.
To request JSON from a URL, you need to send an HTTP GET request to the server and provide the Accept: application/json request header with your request. The Accept header tells the server that our client is expecting JSON.
What's being returned is a JSON string; you need to parse it before you can conveniently use it. Requests can do this for you if you call r.json()
instead of r.text
.
resp = r.json()
print resp['origin']
print resp['headers']['Host']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With