Ticket #17419: json-filter.v2.diff

File json-filter.v2.diff, 3.7 KB (added by carbonXT, 4 years ago)

json template filter with tests and docs - output no longer marked safe

  • django/template/defaultfilters.py

    diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py
    index f93e799..06cf91c 100644
    a b from pprint import pformat 
    99
    1010from django.template.base import Variable, Library, VariableDoesNotExist
    1111from django.conf import settings
    12 from django.utils import formats
     12from django.utils import formats, simplejson
    1313from django.utils.dateformat import format, time_format
    1414from django.utils.encoding import force_unicode, iri_to_uri
    1515from django.utils.html import (conditional_escape, escapejs, fix_ampersands,
    def filesizeformat(bytes): 
    838838        return ugettext("%s TB") % filesize_number_format(bytes / (1024 * 1024 * 1024 * 1024))
    839839    return ugettext("%s PB") % filesize_number_format(bytes / (1024 * 1024 * 1024 * 1024 * 1024))
    840840
     841@register.filter(is_safe=True)
     842def json(value):
     843    """
     844    Returns the json representation of value.
     845
     846    Note that the HTML spec (though not XHTML) declares all text within
     847    <script> tags to be CDATA and therefore does not need escaping.
     848    Thus, when using this filter between <script> tags for such a document,
     849    you'll want to avoid escaping the output: {{ data|json|safe }}
     850    """
     851    return simplejson.dumps(value)
     852
    841853@register.filter(is_safe=False)
    842854def pluralize(value, arg=u's'):
    843855    """
  • docs/ref/templates/builtins.txt

    diff --git a/docs/ref/templates/builtins.txt b/docs/ref/templates/builtins.txt
    index 85d43ce..3358791 100644
    a b For example:: 
    16651665If ``value`` is the list ``['a', 'b', 'c']``, the output will be the string
    16661666``"a // b // c"``.
    16671667
     1668.. templatefilter:: json
     1669
     1670json
     1671^^^^
     1672
     1673.. versionadded:: 1.4
     1674
     1675Coverts a python datastructure of possibly nested dictionaries and lists into
     1676a json string.
     1677
     1678For example::
     1679
     1680    {{ value|json }}
     1681
     1682If ``value`` is the python dictionary with nested list
     1683``{'hello': ['world', 'wide']}``, the output will be the string
     1684``'{"hello": ["world", "wide"]}'``.
     1685
     1686This filter is most often used within ``<script>`` tags. Per the
     1687HTML spec (though not XHTML) all text within ``<script>`` tags is
     1688CDATA and therefore does not need escaping. Thus, when using this
     1689filter in such a situation, you'll want to explicitly mark the output
     1690as safe to avoid html-entity escaping. For example::
     1691
     1692    <script>
     1693        var json_data = {{ value|json|safe }};
     1694    </script>
     1695
    16681696.. templatefilter:: last
    16691697
    16701698last
  • tests/regressiontests/templates/filters.py

    diff --git a/tests/regressiontests/templates/filters.py b/tests/regressiontests/templates/filters.py
    index 54c1267..262304b 100644
    a b def get_filter_tests(): 
    106106        'filter-lower01': ("{% autoescape off %}{{ a|lower }} {{ b|lower }}{% endautoescape %}", {"a": "Apple & banana", "b": mark_safe("Apple &amp; banana")}, u"apple & banana apple &amp; banana"),
    107107        'filter-lower02': ("{{ a|lower }} {{ b|lower }}", {"a": "Apple & banana", "b": mark_safe("Apple &amp; banana")}, u"apple &amp; banana apple &amp; banana"),
    108108
     109        # json filter #17419
     110        'filter-json01': ("{{ data|json }}", {"data": {"hello": ["world", "universe"]}}, u'{&quot;hello&quot;: [&quot;world&quot;, &quot;universe&quot;]}'),
     111        'filter-json02': ("{{ data|json|safe }}", {"data": {"foo": "<bar>"}}, u'{"foo": "<bar>"}'),
     112        'filter-json03': ("{{ data|json|safe }}", {"data": ["foo", 'ba"r']}, u'["foo", "ba\\"r"]'),
     113
    109114        # The make_list filter can destroy existing escaping, so the results are
    110115        # escaped.
    111116        'filter-make_list01': ("{% autoescape off %}{{ a|make_list }}{% endautoescape %}", {"a": mark_safe("&")}, u"[u'&']"),
Back to Top