diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index 79ef6137f52..7c1113bdda8 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -727,6 +727,7 @@ class Template: value: Any, error_value: Any = _SENTINEL, variables: dict[str, Any] | None = None, + parse_result: bool = False, ) -> Any: """Render template with value exposed. @@ -748,7 +749,9 @@ class Template: variables["value_json"] = json_loads(value) try: - return _render_with_context(self.template, compiled, **variables).strip() + render_result = _render_with_context( + self.template, compiled, **variables + ).strip() except jinja2.TemplateError as ex: if error_value is _SENTINEL: _LOGGER.error( @@ -759,6 +762,11 @@ class Template: ) return value if error_value is _SENTINEL else error_value + if not parse_result or self.hass and self.hass.config.legacy_templates: + return render_result + + return self._parse_result(render_result) + def _ensure_compiled( self, limited: bool = False, diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index bf48199d419..90af925ddca 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -1728,6 +1728,26 @@ def test_render_with_possible_json_value_non_string_value(hass: HomeAssistant) - assert tpl.async_render_with_possible_json_value(value) == expected +def test_render_with_possible_json_value_and_parse_result(hass: HomeAssistant) -> None: + """Render with possible JSON value with valid JSON.""" + tpl = template.Template("{{ value_json.hello }}", hass) + result = tpl.async_render_with_possible_json_value( + """{"hello": {"world": "value1"}}""", parse_result=True + ) + assert isinstance(result, dict) + + +def test_render_with_possible_json_value_and_dont_parse_result( + hass: HomeAssistant, +) -> None: + """Render with possible JSON value with valid JSON.""" + tpl = template.Template("{{ value_json.hello }}", hass) + result = tpl.async_render_with_possible_json_value( + """{"hello": {"world": "value1"}}""", parse_result=False + ) + assert isinstance(result, str) + + def test_if_state_exists(hass: HomeAssistant) -> None: """Test if state exists works.""" hass.states.async_set("test.object", "available")