Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print pretty JSON on a html page from a django template?

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>
like image 303
bayman Avatar asked Jul 23 '17 20:07

bayman


People also ask

How show JSON data Pretty in HTML?

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.

What is pretty-print JSON?

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 .


2 Answers

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>
like image 182
Dev Aggarwal Avatar answered Sep 20 '22 20:09

Dev Aggarwal


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)

like image 34
w33b Avatar answered Sep 20 '22 20:09

w33b