diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index 34b19c07f83..85ee1e28309 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -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: diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index 15c6a4b7251..82b6434cf3f 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -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."""