Gre*_*ade 11 django serialization json django-rest-framework
我正在使用django rest_gramework序列化程序来转储我的对象的json:
response = InstallSerializer(Install.objects.all(), many=True).data
return StreamingHttpResponse(response, content_type='application/json')
Run Code Online (Sandbox Code Playgroud)
哪里
class InstallSerializer(serializers.ModelSerializer):
modules = ModuleSerializer(many=True)
class Meta:
model = Install
fields = ('id', 'install_name', 'modules')
Run Code Online (Sandbox Code Playgroud)
等等
但是,这个输出不是"可读的"......它全部都在一行上.
{'id': 1, 'install_name': u'Combat Mission Battle For Normandy', 'modules': [{'id': 1, 'name': u'Combat Mission Battle For Normandy', 'versions': [{'id': 1, 'name': u'1.00-Mac', 'brzs': [1, 2, 3]}]}]}
Run Code Online (Sandbox Code Playgroud)
有没有办法让串行器更好地格式化输出?
(用于调试的外观检查)
注意:我刚刚了解到我输出上面显示的序列化表单的方法甚至没有产生有效的json,尽管它看起来很相似.您必须执行下面接受的答案中显示的json.dump步骤才能获得有效的json,并且作为奖励它也非常好.
Den*_*ehl 10
当您使用rest_framework时,您不应该使用json.dumps自己,因为渲染器会为您完成此工作.您看到的数据是python字典,它是序列化程序的输出.它不会被DRF渲染,因为你正在返回一个Django StreamingHttpResponse.需要渲染此数据才能获得JSON.您是否有理由绕过rest_framework渲染?
否则,这是你的处理程序:
return Response(InstallSerializer(Install.objects.all(), many=True).data)
Run Code Online (Sandbox Code Playgroud)
哪里Response是rest_framework.response.Response.
如果你的客户端需要漂亮的json:rest_framework JSONRenderer支持头部的indent参数Accept(参见文档).
所以当你的客户发送:
Accept: application/json; indent=4
Run Code Online (Sandbox Code Playgroud)
您的JSON将缩进.
我这样做:
class PrettyJsonRenderer(JSONRenderer):
def get_indent(self, accepted_media_type, renderer_context):
return 2
Run Code Online (Sandbox Code Playgroud)
然后PrettyJsonRenderer在您网站的settings.py文件中指定:
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'myapp.util.PrettyJsonRenderer',
)
}
Run Code Online (Sandbox Code Playgroud)
除了Denis Cornehl的回答之外,您还可以强制使用漂亮的打印输出,而无需客户端在其Accept:标题中指定.相反,renderer_context当您调用时,在参数中指定它render():
content = JSONRenderer().render(data, renderer_context={'indent':4})
Run Code Online (Sandbox Code Playgroud)
通过调整Django Rest Framework教程中的示例,您可以漂亮地打印所有JSON序列化对象:
class JSONResponse(HttpResponse):
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data, renderer_context={'indent':4})
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6218 次 |
| 最近记录: |