mirror of
https://github.com/home-assistant/core.git
synced 2025-07-23 21:27:38 +00:00
Add default to from_json (#146211)
This commit is contained in:
parent
fc62a6cd89
commit
97f3bb3da5
@ -2634,9 +2634,14 @@ def ordinal(value):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def from_json(value):
|
def from_json(value, default=_SENTINEL):
|
||||||
"""Convert a JSON string to an object."""
|
"""Convert a JSON string to an object."""
|
||||||
return json_loads(value)
|
try:
|
||||||
|
return json_loads(value)
|
||||||
|
except JSON_DECODE_EXCEPTIONS:
|
||||||
|
if default is _SENTINEL:
|
||||||
|
raise_no_default("from_json", value)
|
||||||
|
return default
|
||||||
|
|
||||||
|
|
||||||
def _to_json_default(obj: Any) -> None:
|
def _to_json_default(obj: Any) -> None:
|
||||||
|
@ -1494,6 +1494,15 @@ def test_from_json(hass: HomeAssistant) -> None:
|
|||||||
).async_render()
|
).async_render()
|
||||||
assert actual_result == expected_result
|
assert actual_result == expected_result
|
||||||
|
|
||||||
|
info = render_to_info(hass, "{{ 'garbage string' | from_json }}")
|
||||||
|
with pytest.raises(TemplateError, match="no default was specified"):
|
||||||
|
info.result()
|
||||||
|
|
||||||
|
actual_result = template.Template(
|
||||||
|
"{{ 'garbage string' | from_json('Bar') }}", hass
|
||||||
|
).async_render()
|
||||||
|
assert actual_result == expected_result
|
||||||
|
|
||||||
|
|
||||||
def test_average(hass: HomeAssistant) -> None:
|
def test_average(hass: HomeAssistant) -> None:
|
||||||
"""Test the average filter."""
|
"""Test the average filter."""
|
||||||
|
Loading…
x
Reference in New Issue
Block a user