Henry Thornton Henry Thornton - 3 months ago 13
JSON Question

Python3, json causes TypeError but simplejson doesn't

I'm running the latest Python3 (with the Anaconda distribution) and have a problem with the standard library installed json which causes the Traceback:

Traceback (most recent call last):
File "C:\Users\Think\Anaconda3\lib\site-packages\werkzeug\serving.py", line 193, in run_wsgi
execute(self.server.app)
File "C:\Users\Think\Anaconda3\lib\site-packages\werkzeug\serving.py", line 181, in execute
application_iter = app(environ, start_response)
File "C:\Users\Think\my_server.py", line 148, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\Think\my_server.py", line 144, in wsgi_app
response = self.dispatch_request(request)
File "C:\Users\Think\my_server.py", line 80, in dispatch_request
return getattr(self, 'on_' + endpoint)(request, **values)
File "C:\Users\Think\my_server.py", line 54, in on_xapi_request
json_data = self.load_json(request.data)
File "C:\Users\Think\my_server.py", line 60, in load_json
return json.loads(data)
File "C:\Users\Think\Anaconda3\lib\json\__init__.py", line 312, in loads
s.__class__.__name__))

TypeError: the JSON object must be str, not 'bytes'


But, simplejson doesn't cause the error.

Answer

Use str.decode('utf-8') before passing to json.loads

I think this line:

return json.loads(data)

is causing the problem. Decode data before passing it to this function.