From 57c34a3d6aa5e6e247d908ca7758aee06f2f3d59 Mon Sep 17 00:00:00 2001 From: KhadeerBasha1232 Date: Fri, 20 Nov 2026 09:57:59 +0530 Subject: [PATCH] Serialize numpy values in template options Options are written into the page with json.dumps, through the tojavascript filter and Jinja's tojson. json can't serialize numpy integers, booleans or arrays, so passing one as an option made rendering fail with "TypeError: Object of type int64 is not JSON serializable". That's common when values come from a DataFrame, for example CircleMarker(radius=row.count) or fit_bounds(df[[...]].values). Give both serializers a default that converts numpy scalars with .item() and arrays with .tolist(). Other unsupported types still raise the same TypeError. Co-Authored-By: Claude Opus 5.5 --- folium/template.py | 16 +++++++++++++++- tests/test_map.py | 41 +++++++++++++++++++++++++++++++++++++++++ tests/test_template.py | 36 ++++++++++++++++++++++++++++++++++++ 3 files changed, 92 insertions(+), 1 deletion(-) diff --git a/folium/template.py b/folium/template.py index b76c9fc1b2..fd1c63d2e7 100644 --- a/folium/template.py +++ b/folium/template.py @@ -1,6 +1,7 @@ import json import jinja2 +import numpy as np from branca.element import Element from folium.utilities import JsCode, TypeJsonValue, camelize @@ -33,9 +34,18 @@ def tojavascript(obj: str | JsCode | dict | list | Element) -> str: return _to_escaped_json(obj) +def _json_default(obj): + """Convert numpy values, which ``json`` can't serialize, to Python ones.""" + if isinstance(obj, np.generic): + return obj.item() + if isinstance(obj, np.ndarray): + return obj.tolist() + raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable") + + def _to_escaped_json(obj: TypeJsonValue) -> str: return ( - json.dumps(obj) + json.dumps(obj, default=_json_default) .replace("<", "\\u003c") .replace(">", "\\u003e") .replace("&", "\\u0026") @@ -47,6 +57,10 @@ class Environment(jinja2.Environment): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.filters["tojavascript"] = tojavascript + self.policies["json.dumps_kwargs"] = { + **self.policies["json.dumps_kwargs"], + "default": _json_default, + } class Template(jinja2.Template): diff --git a/tests/test_map.py b/tests/test_map.py index 1cebf9c2fb..3aa89a479f 100644 --- a/tests/test_map.py +++ b/tests/test_map.py @@ -9,6 +9,7 @@ import numpy as np import pytest +import folium from folium import GeoJson, Map, TileLayer from folium.map import Class, CustomPane, Icon, LayerControl, Marker, Popup, Tooltip from folium.utilities import JsCode, normalize @@ -364,3 +365,43 @@ def test_repeated_save_produces_identical_html(tmp_path): html2 = path2.read_text() html3 = path3.read_text() assert html1 == html2 == html3 + + +@pytest.mark.parametrize( + "add_element, expected", + [ + ( + lambda m: folium.CircleMarker([45, 3], radius=np.int64(5)).add_to(m), + '"radius": 5', + ), + ( + lambda m: folium.TileLayer(max_zoom=np.int64(18)).add_to(m), + '"maxZoom": 18', + ), + ( + lambda m: folium.Marker( + [45, 3], popup=folium.Popup("x", max_width=np.int64(300)) + ).add_to(m), + '"maxWidth": 300,', + ), + ( + lambda m: folium.Marker( + [45, 3], icon=folium.DivIcon(icon_size=np.array([20, 20])) + ).add_to(m), + '"iconSize": [20,20]', + ), + ( + lambda m: m.fit_bounds(np.array([[45.0, 3.0], [46.0, 4.0]])), + "fitBounds([[45.0,3.0],[46.0,4.0]]", + ), + ( + lambda m: m.fit_bounds([[45, 3], [46, 4]], max_zoom=np.int64(5)), + '"maxZoom": 5', + ), + ], +) +def test_numpy_option_values(add_element, expected): + m = folium.Map() + add_element(m) + out = normalize(m.get_root().render()) + assert expected in out diff --git a/tests/test_template.py b/tests/test_template.py index 09c57ce492..4f62461e7f 100644 --- a/tests/test_template.py +++ b/tests/test_template.py @@ -1,3 +1,7 @@ +import json + +import numpy as np +import pytest from branca.element import Element from folium import JsCode @@ -72,3 +76,35 @@ def test_environment_filter(): def test_template_environment_class(): assert Template.environment_class == Environment + + +@pytest.mark.parametrize( + "value, expected", + [ + (np.int64(5), 5), + (np.int32(-3), -3), + (np.float32(0.5), 0.5), + (np.bool_(True), True), + (np.array([[1, 2], [3, 4]]), [[1, 2], [3, 4]]), + ({"radius": np.int64(5)}, {"radius": 5}), + ], +) +def test_to_escaped_json_numpy(value, expected): + assert json.loads(_to_escaped_json(value)) == expected + + +def test_to_escaped_json_unsupported_type(): + with pytest.raises(TypeError, match="object is not JSON serializable"): + _to_escaped_json(object()) + + +def test_tojavascript_with_numpy_values(): + result = tojavascript({"maxZoom": np.int64(18), "iconSize": np.array([20, 20])}) + assert '"maxZoom": 18' in result + assert '"iconSize": [20, 20]' in result + + +def test_tojson_filter_with_numpy_values(): + template = Template("{{ value|tojson }}") + result = template.render(value={"bounds": np.array([[1, 2], [3, 4]])}) + assert json.loads(result) == {"bounds": [[1, 2], [3, 4]]}