Skip to content

Commit 17896f6

Browse files
junrae6454jun.4Rocketknight1
authored
Change JSON serialization to custom json.dumps (#31100)
* Change JSON serialization to custom json.dumps to prevent escaping of "<", ">", "&", "'" * caller has control over the order, remove sort_key=True * Move tojson into a proper function and expose a couple of other args --------- Co-authored-by: jun.4 <[email protected]> Co-authored-by: Matt <[email protected]>
1 parent 1c77b3d commit 17896f6

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

src/transformers/tokenization_utils_base.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1892,8 +1892,13 @@ def _compile_jinja_template(self, chat_template):
18921892
def raise_exception(message):
18931893
raise TemplateError(message)
18941894

1895+
def tojson(x, ensure_ascii=False, indent=None, separators=None, sort_keys=False):
1896+
# We override the built-in tojson filter because Jinja's default filter escapes HTML characters
1897+
# We also expose some options like custom indents and separators
1898+
return json.dumps(x, ensure_ascii=ensure_ascii, indent=indent, separators=separators, sort_keys=sort_keys)
1899+
18951900
jinja_env = ImmutableSandboxedEnvironment(trim_blocks=True, lstrip_blocks=True)
1896-
jinja_env.policies["json.dumps_kwargs"]["ensure_ascii"] = False
1901+
jinja_env.filters["tojson"] = tojson
18971902
jinja_env.globals["raise_exception"] = raise_exception
18981903
return jinja_env.from_string(chat_template)
18991904

0 commit comments

Comments
 (0)