From 4224cb043b1f2f01ceed478f38713d5943f2a521 Mon Sep 17 00:00:00 2001 From: Chris Browet Date: Mon, 8 Nov 2021 15:49:10 +0100 Subject: [PATCH] Allow overriding ensure_ascii in the "to_json" template filter (#54527) * FIX: "ensureascii" to to_json * fixup: parameter name --- homeassistant/helpers/template.py | 4 ++-- tests/helpers/test_template.py | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index f090b28210f..7f3937d41c1 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -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 diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index 557ec81c2dc..dd0c4c96a11 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -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."""