twitter.request and json.loads problem
metawops last edited by
still a beginner at Python, so please be patient.
I'm using the twitter.request function for a Twitter API request.
The result is a tuple consisting of a return code and the actual JSON result.
I want to get hold of that JSON result like this:
if status == 200: result = json.loads(data)
However, I get this error:
Traceback (most recent call last):
File "/private/var/mobile/Containers/Shared/AppGroup/9D2704E0-434A-4879-8FB0-30594FA3A28D/Pythonista3/Documents/addToCollectionIK.py", line 17, in <module>
result = json.loads(data)
File "/var/containers/Bundle/Application/B09EF8B7-CE0F-4572-9748-EC15615DEA7A/Pythonista3.app/Frameworks/PythonistaKit3.framework/pylib/json/init.py", line 312, in loads
TypeError: the JSON object must be str, not 'bytes'
Why is that and what can I do about it? From what I understand the twitter.request function doesn't seem to return the JSON object as a string but as 'bytes' (what's that?). So I need to make a string out of that bytes, right? But how?
(btw, the json.load(data) function doesn't work, either ...)
Thanks a lot,
omz last edited by
bytesis the Python 3 version of
strin Python 3 is equivalent to
unicodein Python 2.
To fix your problem,
data.decode('utf-8')should work (actually
data.decode()should be enough, since utf-8 is the default encoding).
omz last edited by omz
Btw, the reason
twitter.requestgives you a byte string, and not unicode, is that some requests may actually result in binary data (e.g. profile images etc.), and this way, the type of the return value can be the same in all cases.
In Python 2, you don't really see this as a problem because byte strings are silently converted to unicode in a lot of cases, but in Python 3, you have to be explicit (which is often for the better because the Python 2 approach can hide errors from you that only pop up when your data suddenly contains umlauts). If you want to learn more, here's a good presentation on the subject: http://nedbatchelder.com/text/unipain.html