Why is it that in python, I can pretty print JSON with the python example below, but in a django template, it doesn't work? How can I pretty print JSON in a django template?
python:
import requests, json
url = 'https://api.example.com/details'
r = requests.get(url)
json_data = r.json()
json_pretty = json.dumps(json_data, sort_keys=True, indent=4)
print (json_pretty)
django views.py:
def json_list(request):
url = 'https://api.example.com/details'
r = requests.get(url)
json_data = r.json()
json_pretty = json.dumps(json_data, sort_keys=True, indent=4)
context = {
"json_pretty": json_pretty,
}
return render(request, "json_output.html", context)
template:
<div>{{ json_pretty }}</div>
use a <pre> tag to JavaScript pretty prints JSON in HTML. The <pre> need id to show data on it. Where pre tells the browser engine that the content inside is pre-formatted and can be displayed without any modification.
Pretty printing is a form of stylistic formatting including indentation and colouring. JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and for machines to parse and generate. The official Internet media type for JSON is application/json .
Why not just use the pprint
filter?
context["my_json"] = {i: i for i in range(100)}
<pre>{{ my_json }}</pre>
vs
<pre>{{ my_json | pprint }}</pre>
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)
{% 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With