Add template filters to convert objects to and from JSON strings (#27909)

* Added filters to convert objects to and from JSON strings.

* Added extra spacing.

* Removed try/catch to get native exceptions

* Added tests.
pull/28139/head
SteveDinn 2019-10-23 02:51:29 -03:00 committed by Paulus Schoutsen
parent ab22c61764
commit 25fd930d67
2 changed files with 36 additions and 0 deletions

View File

@ -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 @contextfilter
def random_every_time(context, values): def random_every_time(context, values):
"""Choose a random value. """Choose a random value.
@ -916,6 +926,8 @@ class TemplateEnvironment(ImmutableSandboxedEnvironment):
self.filters["timestamp_custom"] = timestamp_custom self.filters["timestamp_custom"] = timestamp_custom
self.filters["timestamp_local"] = timestamp_local self.filters["timestamp_local"] = timestamp_local
self.filters["timestamp_utc"] = timestamp_utc 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["is_defined"] = fail_when_undefined
self.filters["max"] = max self.filters["max"] = max
self.filters["min"] = min self.filters["min"] = min

View File

@ -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): def test_min(hass):
"""Test the min filter.""" """Test the min filter."""
assert template.Template("{{ [1, 2, 3] | min }}", hass).async_render() == "1" assert template.Template("{{ [1, 2, 3] | min }}", hass).async_render() == "1"