0

I've recently starting using the requests library (which is excellent). However when I get a request response via a post method it seems to return a String(unicode) , when I check the type, even though it looks like a dictionary - which makes it more difficult to pull data from it.

Is there a way to have the json data returned in dictionary format, so I can easily extract a couple of fields?

specifically a request like:

>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print(r.text)
{
  ...
  "form": {
    "key2": "value2",
    "key1": "value1"
  },
  ...
}

r.text is a unicode string not a dictionary (even though it looks like one above)?

Yunti
  • 6,761
  • 12
  • 61
  • 106

2 Answers2

3

Use json method of response object.

print r.json()
Dmitry Nedbaylo
  • 2,254
  • 1
  • 20
  • 20
  • And after that the OP could use this post to interpret the json object as a dictionary http://stackoverflow.com/questions/19483351/converting-json-string-to-dictionary-not-list-python You could verify it and add it to your answer if you want. – kartikg3 Jan 23 '15 at 17:03
1

Use Requests built-in json decoder:

r.json()

see: https://requests.readthedocs.io/en/master/user/quickstart/#json-response-content

Railslide
  • 5,344
  • 2
  • 27
  • 34
  • 1
    This link is unfortunately broken now. In following link is active documentation: https://requests.readthedocs.io/en/master/user/quickstart/#json-response-content – Weky Apr 14 '20 at 13:53