Add default to from_json (#146211)

This commit is contained in:
Petro31 2025-06-24 08:27:14 -04:00 committed by GitHub
parent fc62a6cd89
commit 97f3bb3da5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 16 additions and 2 deletions

View File

@ -2634,9 +2634,14 @@ def ordinal(value):
)
def from_json(value):
def from_json(value, default=_SENTINEL):
"""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:

View File

@ -1494,6 +1494,15 @@ def test_from_json(hass: HomeAssistant) -> None:
).async_render()
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:
"""Test the average filter."""