Pretty Print JSON Response from Django's Serialize Method
To get a pretty JSON response from Django's serialize method, you can use the 'json.dumps' function with the 'indent' parameter set to the number of spaces you want to use for indentation. Here is an example:
from django.core import serializers
from django.http import HttpResponse
import json
def my_view(request):
data = serializers.serialize('json', MyModel.objects.all())
response_data = json.dumps(json.loads(data), indent=4)
return HttpResponse(response_data, content_type='application/json')
In this example, 'MyModel' is the name of your Django model. The 'serialize' method returns a string containing the serialized data in JSON format. We use the 'json.loads' function to convert this string to a JSON object, then use 'json.dumps' with 'indent=4' to convert it back to a formatted string with indentation. Finally, we return this string as an HTTP response with the content type set to 'application/json'.
原文地址: http://www.cveoy.top/t/topic/mGn2 著作权归作者所有。请勿转载和采集!