Allow overriding ensure_ascii in the "to_json" template filter (#54527)

* FIX: "ensureascii" to to_json

* fixup: parameter name
pull/59353/head
Chris Browet 2021-11-08 15:49:10 +01:00 committed by GitHub
parent 67c2747027
commit 4224cb043b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 17 additions and 2 deletions

View File

@ -1623,9 +1623,9 @@ def from_json(value):
return json.loads(value)
def to_json(value):
def to_json(value, ensure_ascii=True):
"""Convert an object to a JSON string."""
return json.dumps(value)
return json.dumps(value, ensure_ascii=ensure_ascii)
@pass_context

View File

@ -746,6 +746,21 @@ def test_to_json(hass):
assert actual_result == expected_result
def test_to_json_string(hass):
"""Test the object to JSON string filter."""
# Note that we're not testing the actual json.loads and json.dumps methods,
# only the filters, so we don't need to be exhaustive with our sample JSON.
actual_value_ascii = template.Template(
"{{ 'Bar ҝ éèà' | to_json }}", hass
).async_render()
assert actual_value_ascii == '"Bar \\u049d \\u00e9\\u00e8\\u00e0"'
actual_value = template.Template(
"{{ 'Bar ҝ éèà' | to_json(ensure_ascii=False) }}", hass
).async_render()
assert actual_value == '"Bar ҝ éèà"'
def test_from_json(hass):
"""Test the JSON string to object filter."""