Fix to_json with ensure_ascii emitting invalid JSON for NaN and Infinity (#187669)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Raman Gupta
2026-10-20 22:55:13 -04:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 254f3d3ec4
commit 70036199a6
2 changed files with 38 additions and 2 deletions
@@ -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
@@ -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."""