Skip to content

Instantly share code, notes, and snippets.

@jackiect
Forked from amacneil/json.py
Created March 18, 2021 03:24

Revisions

  1. @amacneil amacneil revised this gist Feb 16, 2016. 1 changed file with 2 additions and 1 deletion.
    3 changes: 2 additions & 1 deletion json.py
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,4 @@
    from django.core.serializers.json import DjangoJSONEncoder
    from django.template import Library
    from json import dumps as json_dumps

    @@ -34,7 +35,7 @@ def json(data):
    '>': '\\u003e',
    '\u2028': '\\u2028',
    '\u2029': '\\u2029'}
    json_str = json_dumps(data)
    json_str = json_dumps(data, cls=DjangoJSONEncoder)

    for (c, d) in unsafe_chars.items():
    json_str = json_str.replace(c, d)
  2. @amacneil amacneil revised this gist Feb 16, 2016. No changes.
  3. @amacneil amacneil created this gist Feb 16, 2016.
    42 changes: 42 additions & 0 deletions json.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    from django.template import Library
    from json import dumps as json_dumps

    register = Library()


    @register.filter
    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:
    <script>
    var user = {{ data|json|safe }};
    </script>
    Escaped characters taken from Rails json_escape() helper:
    https://github.com/rails/rails/blob/v4.2.5/activesupport/lib/active_support/core_ext/string/output_safety.rb#L60-L113
    """
    unsafe_chars = {
    '&': '\\u0026',
    '<': '\\u003c',
    '>': '\\u003e',
    '\u2028': '\\u2028',
    '\u2029': '\\u2029'}
    json_str = json_dumps(data)

    for (c, d) in unsafe_chars.items():
    json_str = json_str.replace(c, d)

    return json_str