JSONRenderer won't serialize: b'{“id”:“111

2020-03-26 07:12发布

问题:

I've problem with serializing object using JSONRenderer.

I'm using django-rest-framework and I've serialized object:

  pk = kwargs['pk']
  tube = Tube.objects.get(id=pk)

  serialized_tube = TubeSerializer(tube)

serialized_tube.data looks like this:

{'id': '11122211133311'}

Unfortunately I can't serialize this using JSONRenderer, because the code

  tube_json = JSONRenderer().render(serialized_tube.data)
  return Response(tube_json)

gives following error

b'{"id":"11122211133311"}' is not JSON serializable

whereas

  tube_json = json.dumps(serialized_tube.data)
  return Response(tube_json)

works well...

I'm using Python3.4.3

回答1:

The issue is not in your JSONRenderer() line, but in the line below it where you return it as a Response.

Django REST framework provides a custom Response object that will automatically be rendered as whatever the accepted renderer was, converting native Python structures into a rendered version (in this case, JSON structures). So a Python dictionary will be converted to a JSON object, and a Python list will be converted to a JSON array, etc.

Right now you are serializing your data to a JSON string then passing it to Response, where you are expecting it to be re-serialized into JSON. You can't serialize a string into JSON (you need an object or array wrapping it), which is why you are seeing the error.

The solution is to not call JSONRenderer ahead of time, and just pass the serializer data to Response.