12
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?

1 Answer 1

31

What's being returned is a JSON string; you need to parse it before you can conveniently use it. The requests library can do this for you if you call r.json() instead of r.text.

resp = r.json()
print resp['origin']
print resp['headers']['Host']
Sign up to request clarification or add additional context in comments.

3 Comments

r.text may use a wrong character encoding, just use r.json() always
why I get string from json() ?
could be various reasons.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.