本文介绍了JSONRenderer不会序列化:b'{“id”:“11122211133311”}“不是JSON可序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用JSONRenderer对序列化对象有问题。

I've problem with serializing object using JSONRenderer.

我正在使用 django-rest-framework 我已经序列化了对象:

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 如下所示:

不幸的是,我无法使用JSONRenderer序列化它,因为代码

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

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

提供以下错误

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

工作得很好...

我使用的是Python3.4.3

I'm using Python3.4.3

推荐答案

问题不在您的 JSONRenderer()行中,而在下面的行它返回它作为一个响应

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

Django REST框架提供了一个定制的响应将自动呈现为接受的渲染器的对象,将本机Python结构转换为呈现版本(在本例中为JSON结构)。所以一个Python字典将被转换成一个JSON对象,一个Python列表将被转换成一个JSON数组等。

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.

现在你将数据序列化到一个然后将JSON字符串传递给 Response ,您希望将其重新序列化为JSON。您不能将字符串序列化为JSON(您需要一个对象或数组包装),这就是为什么您看到错误。

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.

解决方案是不要调用 JSONRenderer 提前,将串行器数据传递到响应

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

这篇关于JSONRenderer不会序列化:b'{“id”:“11122211133311”}“不是JSON可序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 20:42