from django.http.response import JsonResponse
from rest_framework.response import Response
data = { "data": [
{"example":"a","id": 1},
{"example":"b","id": 2},
{"example":"c","id": 3},
],
"numItem": 3
}
# case 1
return JsonResponse(data, json_dumps_params={"indent":4})
# case 2
return Response(json.dumps(data, indent=4), content_type='application/json')
# case 3
json_data = json.dumps(data, indent=4)
return Response(json.loads(json_data), content_type='application/json')
I see that Response
is returning a string. Meaning json.dumps(data, indent=4)
actually returns a string and I am just passing the stringed JSON with \n
and space
(formatting).
But why does the formatting work properly with JsonResponse
?
How could I make Response
also returns formatted JSON and displayed correctly?
And, why is the JSON string passed not being displayed with the actual newline?
according to this you just need to override get_renderer_context
to something like this:
def get_renderer_context(self):
context = super().get_renderer_context()
context['indent'] = 4
return context