Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: tojson filter now respects autoescape #1937

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ Unreleased
- Use modern packaging metadata with ``pyproject.toml`` instead of ``setup.cfg``.
:pr:`1793`
- Use ``flit_core`` instead of ``setuptools`` as build backend.
- Fixed `autoescape=False` not working for builtin filter `tojson`.
:issue:`1934`


Version 3.1.3
Expand Down
11 changes: 9 additions & 2 deletions src/jinja2/filters.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Built-in template filters used with the ``|`` operator."""
import json
import math
import random
import re
Expand Down Expand Up @@ -1680,9 +1681,9 @@ async def do_rejectattr(
@pass_eval_context
def do_tojson(
eval_ctx: "EvalContext", value: t.Any, indent: t.Optional[int] = None
) -> Markup:
) -> t.Union[str, Markup]:
"""Serialize an object to a string of JSON, and mark it safe to
render in HTML. This filter is only for use in HTML documents.
render in HTML if autoescape.

The returned string is safe to render in HTML documents and
``<script>`` tags. The exception is in HTML attributes that are
Expand All @@ -1703,6 +1704,12 @@ def do_tojson(
kwargs = kwargs.copy()
kwargs["indent"] = indent

if not eval_ctx.autoescape:
if dumps is None:
dumps = json.dumps

return soft_str(dumps(value, **kwargs))

return htmlsafe_json_dumps(value, dumps=dumps, **kwargs)


Expand Down
6 changes: 6 additions & 0 deletions tests/test_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -812,6 +812,12 @@ def test_func_reject_attr(self, env):
assert tmpl.render(users=users) == "jane"

def test_json_dump(self):
env = Environment(autoescape=False)
t = env.from_string("{{ x|tojson }}")
assert t.render(x={"foo": "bar"}) == '{"foo": "bar"}'
assert t.render(x="\"ba&r'") == '"\\"ba&r\'"'
assert t.render(x="<bar>") == '"<bar>"'

env = Environment(autoescape=True)
t = env.from_string("{{ x|tojson }}")
assert t.render(x={"foo": "bar"}) == '{"foo": "bar"}'
Expand Down
Loading