diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index 9af1998e894..1d9ca691451 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -884,6 +884,16 @@ def ordinal(value): ) +def from_json(value): + """Convert a JSON string to an object.""" + return json.loads(value) + + +def to_json(value): + """Convert an object to a JSON string.""" + return json.dumps(value) + + @contextfilter def random_every_time(context, values): """Choose a random value. @@ -916,6 +926,8 @@ class TemplateEnvironment(ImmutableSandboxedEnvironment): self.filters["timestamp_custom"] = timestamp_custom self.filters["timestamp_local"] = timestamp_local self.filters["timestamp_utc"] = timestamp_utc + self.filters["to_json"] = to_json + self.filters["from_json"] = from_json self.filters["is_defined"] = fail_when_undefined self.filters["max"] = max self.filters["min"] = min diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index cc1f7707df6..b69fdb17e35 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -501,6 +501,30 @@ def test_timestamp_local(hass): ) +def test_to_json(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. + expected_result = '{"Foo": "Bar"}' + actual_result = template.Template( + "{{ {'Foo': 'Bar'} | to_json }}", hass + ).async_render() + assert actual_result == expected_result + + +def test_from_json(hass): + """Test the JSON string to object 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. + expected_result = "Bar" + actual_result = template.Template( + '{{ (\'{"Foo": "Bar"}\' | from_json).Foo }}', hass + ).async_render() + assert actual_result == expected_result + + def test_min(hass): """Test the min filter.""" assert template.Template("{{ [1, 2, 3] | min }}", hass).async_render() == "1"