Ticket #17419: json-filter.diff

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

json template filter with tests and docs

  • django/template/defaultfilters.py

    diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py
    index 9eabb6d..dfdf817 100644
    a b from pprint import pformat 
    99
    1010from django.template.base import Variable, Library
    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): 
    832832        return ugettext("%s TB") % filesize_number_format(bytes / (1024 * 1024 * 1024 * 1024))
    833833    return ugettext("%s PB") % filesize_number_format(bytes / (1024 * 1024 * 1024 * 1024 * 1024))
    834834
     835@register.filter(is_safe=True)
     836def json(value):
     837    """
     838    Returns the json representation of value.
     839
     840    This filter is most often used within <script> tags. Per the HTML
     841    spec (though not XHTML) all text within <script> tags is CDATA and
     842    therefore does not need escaping. Thus, the output is marked safe,
     843    even though no escaping is done.
     844
     845    When using this filter outside <script> tags, you must explicitly
     846    force_escape the output: {{ data|json|force_escape }}.
     847    """
     848    return mark_safe(simplejson.dumps(value))
     849
    835850@register.filter(is_safe=False)
    836851def pluralize(value, arg=u's'):
    837852    """
  • docs/ref/templates/builtins.txt

    diff --git a/docs/ref/templates/builtins.txt b/docs/ref/templates/builtins.txt
    index 1499e2a..da71370 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    <script>
     1681        var json_data = {{ value|json }};
     1682    </script>
     1683
     1684If ``value`` is the python dictionary with nested list
     1685``{'hello': ['world', 'wide']}``, the output will be the string
     1686``'{"hello": ["world", "wide"]}'``.
     1687
     1688This filter is most often used within ``<script>`` tags. Per the
     1689HTML spec (though not XHTML) all text within ``<script>`` tags is
     1690CDATA and therefore does not need escaping. Thus, the output of this filter
     1691is marked safe, even though no escaping is done.
     1692
     1693When using this filter outside ``<script>`` tags, you must explicitly
     1694force_escape the output. For example::
     1695
     1696    {{ value|json|force_escape }}
     1697
    16681698.. templatefilter:: last
    16691699
    16701700last
  • tests/regressiontests/templates/filters.py

    diff --git a/tests/regressiontests/templates/filters.py b/tests/regressiontests/templates/filters.py
    index 54c1267..52382a3 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'{"hello": ["world", "universe"]}'),
     111        'filter-json02': ("{{ data|json }}", {"data": {"foo": "<bar>"}}, u'{"foo": "<bar>"}'),
     112        'filter-json03': ("{{ data|json }}", {"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