Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion folium/template.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import json

import jinja2
import numpy as np
from branca.element import Element

from folium.utilities import JsCode, TypeJsonValue, camelize
Expand Down Expand Up @@ -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")
Expand All @@ -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):
Expand Down
41 changes: 41 additions & 0 deletions tests/test_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
36 changes: 36 additions & 0 deletions tests/test_template.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import json

import numpy as np
import pytest
from branca.element import Element

from folium import JsCode
Expand Down Expand Up @@ -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]]}
Loading