0

Why do I get

ValueError: No JSON object could be decoded

from this code:

import urllib.request,json 

n = urllib.request.urlopen("http://graph.facebook.com/55")
d = json.loads(str(n.readall()))

The full error:

Traceback (most recent call last):
  File "<pyshell#41>", line 1, in <module>
    d= json.loads(str(n.readall()))
  File "C:\Python33\lib\json\__init__.py", line 309, in loads
    return _default_decoder.decode(s)
  File "C:\Python33\lib\json\decoder.py", line 352, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Python33\lib\json\decoder.py", line 370, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

The output of str(n.readall()):

'b\'{"id":"55","name":"Jillian Copeland","first_name":"Jillian","last_name":"Copeland","username":"JCoMD","gender":"female","locale":"en_US"}\''

Maybe the b is throwing it off?

If that is the issue, how do I convert the binary stream from the readall to a string and not have that b?

I am trying to learn a little python so please keep that in mind.

I am using Python 3.3 in Windows.

1

1 Answer 1

4

I believe that this is an exact duplicate of this question, but sadly there's no accepted answer.

On my end, this works:

import urllib.request,json 

n = urllib.request.urlopen("http://graph.facebook.com/55")
d= json.loads(n.readall().decode('utf-8'))
Sign up to request clarification or add additional context in comments.

3 Comments

If I don't decode, I get this: TypeError: can't use a string pattern on a bytes-like object. I am using python 3.1 instead of 3.3, so that may be why though.
What I am missing here though, is how we determine that the response is UTF-8, and not in some other encoding. I didn't look into how to pull that from the urllib request.
The content-type header tells you that.

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.