Django – Format JSON strings to be human-readable in Admin pages

I’m storing a JSON blob in a TextField and indexing these fields using Elasticsearch. Unfortunately my JSON strings show up as as an ugly single line when I look at the entries in the Admin panel.

It is not pleasing to me, and it reduces the functionality of the Admin pages. I’d like to be able to read these objects easily even if Django doesn’t inherently handle them (outside of clunky custom JSONFields or mandating Postgres as a backend). Ideally I could call something like PrettyPrinter to properly indent the fields in the object.

The solution?

When you call json.dumps(), add an indent=N argument.

person.dblob = json.dumps(stuff_dict, indent=4)

Now when you look at the contents of this field in the Admin panel, they’ll be prettily-formatted.

There is one caveat– if you make the JSON field read only, it converts to HTML and none of the indentation displays as intended.

(This is fake data.)

Django pretty JSON

Leave a Reply