How to get pretty output from rest_framework serializer

django, django-rest-framework, json, serialization

Solution

When you are using rest_framework you shouldn't use `json.dumps` yourself, since the renderers do this work for you. The data you see is the python dictionary, which is the output of the serializer. It does not get rendered by DRF, because you are are returning a Django `StreamingHttpResponse`. This data needs to be rendered to get your JSON. Is there a reason for you bypassing the rest_framework rendering?

Otherwise, this is your Handler:

return Response(InstallSerializer(Install.objects.all(), many=True).data)

Where `Response` is `rest_framework.response.Response`.

If your client needs pretty json: The rest_framework `JSONRenderer` supports the `indent` argument for the `Accept` header (see the docs).

So when your client sends:

Accept: application/json; indent=4

Your JSON will be indented.

Problem

I'm using the django rest_gramework serializer, to dump json of my objects: ``` response = InstallSerializer(Install.objects.all(), many=True).data return StreamingHttpResponse(response, content_type='application/json') ``` where ``` class InstallSerializer(serializers.ModelSerializer): modules = ModuleSerializer(many=True) class Meta: model = Install fields = ('id', 'install_name', 'modules') ``` etc. However, this output is not "readable" ... it comes all on one line. ``` {'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]}]}]} ``` Is there a way to askk the serializer to format the output better? (For visual inspection for debug) Note: I just learned that my approach for outputting the serialized form shown above does not even produce valid json, though it looks similar. You have to do the json.dump step shown in the accepted answer below to get valid json, and as a bonus it is pretty as well.

Original source