Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python requests: get attributes from returned JSON string

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?

like image 918
user3166599 Avatar asked Apr 22 '14 23:04

user3166599


People also ask

How do you read a JSON response in Python?

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.

How extract specific data from JSON Python?

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.

How does Python read JSON attributes?

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.

How do I get JSON response?

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.


1 Answers

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']
like image 97
Erik Kaplun Avatar answered Nov 15 '22 19:11

Erik Kaplun