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.7k5 gold badges66 silver badges70 bronze badges
asked Apr 15, 2013 at 15:14
SamFisher83
4,0059 gold badges42 silver badges54 bronze badges
-
1possible duplicate of Use "byte-like object" from urlopen.read with json?Martijn Pieters– Martijn Pieters2013年04月15日 15:24:33 +00:00Commented Apr 15, 2013 at 15:24
1 Answer 1
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'))
answered Apr 15, 2013 at 15:22
Bill Lynch
82.4k16 gold badges133 silver badges181 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Bill Lynch
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
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.
Martijn Pieters
The
content-type header tells you that.lang-py