Skip to content

Commit 7b4393d

Browse files
committed
Adding to_json filter and a test for it.
1 parent fd7970c commit 7b4393d

File tree

2 files changed

+13
-0
lines changed

2 files changed

+13
-0
lines changed

jinja2/filters.py

+7
Original file line numberDiff line numberDiff line change
@@ -635,6 +635,12 @@ def do_batch(value, linecount, fill_with=None):
635635
yield tmp
636636

637637

638+
def do_json(value):
639+
"""A filter that outputs Python objects as JSON"""
640+
import json
641+
return json.dumps(value)
642+
643+
638644
def do_round(value, precision=0, method='common'):
639645
"""Round the number to a given precision. The first
640646
parameter specifies the precision (default is ``0``), the
@@ -993,4 +999,5 @@ def _select_or_reject(args, kwargs, modfunc, lookup_attr):
993999
'wordcount': do_wordcount,
9941000
'wordwrap': do_wordwrap,
9951001
'xmlattr': do_xmlattr,
1002+
'to_json': do_json,
9961003
}

tests/test_filters.py

+6
Original file line numberDiff line numberDiff line change
@@ -556,3 +556,9 @@ def __init__(self, id, name):
556556
tmpl = env.from_string('{{ users|rejectattr("id", "odd")|'
557557
'map(attribute="name")|join("|") }}')
558558
assert tmpl.render(users=users) == 'jane'
559+
560+
def test_json(self, env):
561+
env = Environment()
562+
obj = ['foo', {'bar': ('baz', None, 1.0, 2)}]
563+
tmpl = env.from_string('{{ obj|to_json }}')
564+
assert tmpl.render(obj=obj) == '["foo", {"bar": ["baz", null, 1.0, 2]}]'

0 commit comments

Comments
 (0)