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
parent
ab22c61764
commit
25fd930d67
|
@ -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
|
||||
|
|
|
@ -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"
|
||||
|
|
Loading…
Reference in New Issue