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
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!
- How can I best find out how django works internally?
- Reverse Queryset Order in Django
- How to resolve the "psycopg2.errors.UndefinedTable: relation "auth_user" does not exist" when running django unittests on Travis