Ticket #17419: json-filter.v4.diff

File json-filter.v4.diff, 2.2 KB (added by neaf, 13 years ago)

Add test for invalid argument (not JSON serializable)

  • django/template/defaultfilters.py

    diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py
    index 06cf91c..e0f350d 100644
    a b def json(value):  
    848848    Thus, when using this filter between <script> tags for such a document,
    849849    you'll want to avoid escaping the output: {{ data|json|safe }}
    850850    """
    851     return simplejson.dumps(value)
     851    try:
     852        return simplejson.dumps(value)
     853    except TypeError:
     854        return ''
    852855
    853856@register.filter(is_safe=False)
    854857def pluralize(value, arg=u's'):
  • docs/ref/templates/builtins.txt

    diff --git a/docs/ref/templates/builtins.txt b/docs/ref/templates/builtins.txt
    index a28bca5..a05d163 100644
    a b as safe to avoid html-entity escaping. For example::  
    16931693        var json_data = {{ value|json|safe }};
    16941694    </script>
    16951695
    1696 Remember that JSON marked as safe will contain unescaped strings and those need
    1697 to be properly handled in the receiver.
     1696.. note::
     1697
     1698    Remember that JSON marked as safe will contain unescaped strings and those need
     1699    to be properly handled in the receiver.
    16981700
    16991701.. templatefilter:: last
    17001702
  • tests/regressiontests/templates/filters.py

    diff --git a/tests/regressiontests/templates/filters.py b/tests/regressiontests/templates/filters.py
    index 262304b..644fb8b 100644
    a b def get_filter_tests():  
    108108
    109109        # json filter #17419
    110110        '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"]'),
     111        'filter-json02': ("{{ data|json }}", {"data": object()}, u''),
     112        'filter-json03': ("{{ data|json|safe }}", {"data": {"foo": "<bar>"}}, u'{"foo": "<bar>"}'),
     113        'filter-json04': ("{{ data|json|safe }}", {"data": ["foo", 'ba"r']}, u'["foo", "ba\\"r"]'),
    113114
    114115        # The make_list filter can destroy existing escaping, so the results are
    115116        # escaped.
Back to Top