How to print pretty JSON on a html page from a django template?
Why not just use the pprint
filter?
view
context["my_json"] = {i: i for i in range(100)}
template
<pre>{{ my_json }}</pre>
vs
<pre>{{ my_json | pprint }}</pre>
Screnshot
Or if you want something even better, create a custom filter
templatetags/extras.py
import json
from django import template
register = template.Library()
@register.filter
def pretty_json(value):
return json.dumps(value, indent=4)
template
{% load extras %}
<pre>{{ my_json | pretty_json }}</pre>
If you just want to keep your indent, You can use
return HttpResponse(json_pretty,content_type="application/json")
If it is a must to use django template, you can use the HTML <pre>
tag as suggested by Klaus.
So your template becomes
<pre>{{ json_pretty }}</pre>