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

15👍

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>

28👍

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

enter image description here

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>

4👍

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)

1👍

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!

👤Nifled

Leave a comment