0

I have written the following code to read sample JSON data from url,

HEADER = {"content-type": "application/josn"}

session = requests.Session()
session.verify = True
session.headers = HEADER

output = session.request("GET", "https://jsonplaceholder.typicode.com/todos/1", timeout=30)

If I print output I get,

<Response [200]>

If I do,

output = session.request("GET", "https://jsonplaceholder.typicode.com/todos/1", timeout=30).json()

I get actual json content,

{u'completed': False, u'userId': 1, u'id': 1, u'title': u'delectus aut autem'}

But when I do,

output = session.request("GET", "https://jsonplaceholder.typicode.com/todos/1", timeout=30)
print(json.loads(output))

I get,

  File "/usr/lib64/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer

Can someone please give an example to me when should I use .json() and when json.loads()?

3
  • Possible dupe: TypeError: the JSON object must be str, not 'bytes' Commented Oct 16, 2018 at 3:56
  • 1
    A bit irrelevant to the question at hand, but your HEADER declaration has a typo: application/josn should be application/json. Commented Oct 16, 2018 at 3:58
  • can someone please tell me why am I down voted ? i can add more details if needed, but please leave a comment at least. Commented Oct 16, 2018 at 4:02

1 Answer 1

6

The .json is just a shortcut of json.loads() when the response is a json.

print(json.loads(output))

is not working because you need to get the body of the request, i think it is

print(json.loads(output.text))

Sign up to request clarification or add additional context in comments.

3 Comments

This is correct - output in the second example in the OP returns a Response-type object, which is not a datatype json.loads() accepts as the s argument. In fact, the only accepted datatype is str of unicode (source).
thank you, how does .json() automatically gets the output.text?
@MaverickD because is a method of the response object

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.