[Fixed]-How to print pretty JSON on a html page from a django template?


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>


Why not just use the pprint filter?


context["my_json"] = {i: i for i in range(100)}


<pre>{{ my_json }}</pre>
<pre>{{ my_json | pprint }}</pre>


enter image description here

Or if you want something even better, create a custom filter


import json

from django import template

register = template.Library()

def pretty_json(value):
    return json.dumps(value, indent=4)


{% load extras %}
<pre>{{ my_json | pretty_json }}</pre>


I had to use a combination of answers to get what I needed. The missing thing I needed was the filter linebreaks

So in my views.py I have a function

def foobar(request, test_id):
    json_response = json.dumps(example_dict, indent=3)
    return render(request, 'foo/bar.html', {"json_string": json_response})

and in my django template

<pre>{{ json_response | linebreaks }}</pre>

My json string had a bunch of \n in it so this made it look nice by removing those (might be caused by mongoengine objects)


The reason it doesn’t pretty up is because it renders to HTML, which handles spacing different depending on the tags you put it in. Your best bet would be to use a syntax highlighting library. They are usually simple to set up. There are many of them, like highlight.js, prism and many, many more.

I forgot to mention the Pythonic library for syntax highlighting, Pygments!


Leave a comment