JSONRenderer will not be serialized: b '{"id": "11122211133311"}' is not JSON serializable

I have a problem serializing an object using JSONRenderer.

I am using django-rest-framework

and I have a serialized object:

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

  serialized_tube = TubeSerializer(tube)

      

serialized_tube.data

as follows:

{'id': '11122211133311'}

Unfortunately I cannot serialize this with JSONRenderer because the code

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

      

gives the following error

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

then

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

      

works well ...

I am using Python3.4.3

+3


source to share


1 answer


The problem is not your line JSONRenderer()

, but the line below where you return it as Response

.

The Django REST framework provides a custom object Response

that will automatically render as any accepted renderer, converting native Python structures to the rendered version (in this case, JSON structures). This way the Python dictionary will be converted to a JSON object, and the Python list will be converted to a JSON array, etc.



Right now, you are serializing your data to a JSON string and then passing it to Response

where you expect it to be re-serialized to JSON. You cannot serialize a string to JSON (you need an object or array wrapping it), which is why you see an error.

The solution is to not call JSONRenderer

ahead of time and just pass the serializer data to Response

.

+2


source







All Articles