From 70036199a60a3965e96fed33692b597506efcd6b Mon Sep 17 00:00:00 2001 From: Raman Gupta <7243222+raman325@users.noreply.github.com> Date: Tue, 20 Oct 2026 22:55:13 -0400 Subject: [PATCH] Fix to_json with ensure_ascii emitting invalid JSON for NaN and Infinity (#187669) Co-authored-by: Claude Opus 5.5 --- .../template/extensions/serialization.py | 11 +++++-- .../template/extensions/test_serialization.py | 29 +++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/homeassistant/helpers/template/extensions/serialization.py b/homeassistant/helpers/template/extensions/serialization.py index baaca554c4e9..22715d78c59c 100644 --- a/homeassistant/helpers/template/extensions/serialization.py +++ b/homeassistant/helpers/template/extensions/serialization.py @@ -1,5 +1,6 @@ """Serialization functions for Home Assistant templates.""" +from functools import partial import json import logging from struct import error as StructError, pack, unpack_from @@ -121,12 +122,18 @@ class SerializationExtension(BaseTemplateExtension): if ensure_ascii: # For those who need ascii, we can't use orjson, # so we fall back to the json library. - return json.dumps( - value, + dumps = partial( + json.dumps, ensure_ascii=ensure_ascii, indent=2 if pretty_print else None, sort_keys=sort_keys, ) + try: + return dumps(value, allow_nan=False) + except ValueError: + # Serialize NaN and Infinity as null, like orjson does + value = json.loads(json.dumps(value), parse_constant=lambda _: None) + return dumps(value) option = ( _ORJSON_PASSTHROUGH_OPTIONS diff --git a/tests/helpers/template/extensions/test_serialization.py b/tests/helpers/template/extensions/test_serialization.py index 98f5ccd007fc..43fdd925a79e 100644 --- a/tests/helpers/template/extensions/test_serialization.py +++ b/tests/helpers/template/extensions/test_serialization.py @@ -1,6 +1,7 @@ """Test serialization functions for Home Assistant templates.""" import json +import math import orjson import pytest @@ -86,6 +87,34 @@ def test_to_json_ensure_ascii(hass: HomeAssistant) -> None: assert actual_result == expected_result +@pytest.mark.parametrize( + ("value", "expected"), + [ + pytest.param(math.nan, "null", id="nan"), + pytest.param( + {"a": math.inf, "b": [-math.inf, 1.5]}, + '{"a": null, "b": [null, 1.5]}', + id="nested", + ), + ], +) +def test_to_json_ensure_ascii_non_finite_floats( + hass: HomeAssistant, value: object, expected: str +) -> None: + """Test to_json with ensure_ascii serializes NaN and Infinity as null.""" + actual_result = render( + hass, + "{{ value | to_json(ensure_ascii=True) }}", + {"value": value}, + parse_result=False, + ) + assert actual_result == expected + default_result = render( + hass, "{{ value | to_json }}", {"value": value}, parse_result=False + ) + assert json.loads(actual_result) == json.loads(default_result) + + def test_from_json(hass: HomeAssistant) -> None: """Test the JSON string to object filter."""