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.

doelleri
  • 19,232
  • 5
  • 61
  • 65
SamFisher83
  • 3,937
  • 9
  • 39
  • 52
  • 1
    possible duplicate of [Use "byte-like object" from urlopen.read with json?](http://stackoverflow.com/questions/10846112/use-byte-like-object-from-urlopen-read-with-json) – Martijn Pieters Apr 15 '13 at 15:24

1 Answers1

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'))
Community
  • 1
  • 1
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
  • 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. – Bill Lynch Apr 15 '13 at 15:23
  • 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. – Bill Lynch Apr 15 '13 at 15:25
  • The `content-type` header tells you that. – Martijn Pieters Apr 15 '13 at 15:26