Skip to content

Instantly share code, notes, and snippets.

@amacneil amacneil/
Last active Jul 10, 2018

What would you like to do?
Safely JSON-encode objects in your Django template
from django.core.serializers.json import DjangoJSONEncoder
from django.template import Library
from json import dumps as json_dumps
register = Library()
def json(data):
Safely JSON-encode an object.
To protect against XSS attacks, HTML special characters (<, >, &) and unicode newlines
are replaced by escaped unicode characters. Django does not escape these characters
by default.
Output of this method is not marked as HTML safe. If you use it inside an HTML
attribute, it must be escaped like regular data:
<div data-user="{{ data|json }}">
If you use it inside a <script> tag, then the output does not need to be escaped,
so you can mark it as safe:
var user = {{ data|json|safe }};
Escaped characters taken from Rails json_escape() helper:
unsafe_chars = {
'&': '\\u0026',
'<': '\\u003c',
'>': '\\u003e',
'\u2028': '\\u2028',
'\u2029': '\\u2029'}
json_str = json_dumps(data, cls=DjangoJSONEncoder)
for (c, d) in unsafe_chars.items():
json_str = json_str.replace(c, d)
return json_str

This comment has been minimized.

Copy link

acdha commented Mar 1, 2016

@amacneil – thanks for contributing this. I was just looking to do the same thing & that saves the trouble. What license are you releasing this under – the same as Django core?


This comment has been minimized.

Copy link

therefromhere commented Sep 29, 2016

@amacneil I'd like to get this change applied to the Django-jsonify package, would you be happy for me to make a PR based on this gist?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.