Skip to content

Commit 762c876

Browse files
authored
Fix topojson invalid object path (#1665)
* Fix Topojson object path * add tests * Fix test
1 parent 0b05071 commit 762c876

3 files changed

Lines changed: 40 additions & 1 deletion

File tree

folium/features.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
get_bounds,
2525
get_obj_in_upper_tree,
2626
image_to_url,
27+
javascript_identifier_path_to_array_notation,
2728
none_max,
2829
none_min,
2930
parse_options,
@@ -901,7 +902,7 @@ class TopoJson(JSCSSMixin, Layer):
901902
var {{ this.get_name() }} = L.geoJson(
902903
topojson.feature(
903904
{{ this.get_name() }}_data,
904-
{{ this.get_name() }}_data.{{ this.object_path }}
905+
{{ this.get_name() }}_data{{ this._safe_object_path }}
905906
),
906907
{
907908
{%- if this.smooth_factor is not none %}
@@ -949,6 +950,9 @@ def __init__(
949950
self.data = data
950951

951952
self.object_path = object_path
953+
self._safe_object_path = javascript_identifier_path_to_array_notation(
954+
object_path
955+
)
952956

953957
if style_function is None:
954958

folium/utilities.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -493,3 +493,12 @@ def parse_options(**kwargs):
493493
def escape_backticks(text):
494494
"""Escape backticks so text can be used in a JS template."""
495495
return re.sub(r"(?<!\\)`", r"\`", text)
496+
497+
498+
def escape_double_quotes(text):
499+
return text.replace('"', r"\"")
500+
501+
502+
def javascript_identifier_path_to_array_notation(path):
503+
"""Convert a path like obj1.obj2 to array notation: ["obj1"]["obj2"]."""
504+
return "".join(f'["{escape_double_quotes(x)}"]' for x in path.split("."))

tests/test_utilities.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,10 @@
77
_is_url,
88
camelize,
99
deep_copy,
10+
escape_double_quotes,
1011
get_obj_in_upper_tree,
1112
if_pandas_df_convert_to_numpy,
13+
javascript_identifier_path_to_array_notation,
1214
parse_options,
1315
validate_location,
1416
validate_locations,
@@ -189,3 +191,27 @@ def test_parse_options():
189191
)
190192
def test_is_url(url):
191193
assert _is_url(url) is True
194+
195+
196+
@pytest.mark.parametrize(
197+
"text,result",
198+
[
199+
("bla", "bla"),
200+
('bla"bla', r"bla\"bla"),
201+
('"bla"bla"', r"\"bla\"bla\""),
202+
],
203+
)
204+
def test_escape_double_quotes(text, result):
205+
assert escape_double_quotes(text) == result
206+
207+
208+
@pytest.mark.parametrize(
209+
"text,result",
210+
[
211+
("bla", '["bla"]'),
212+
("obj-1.obj2", '["obj-1"]["obj2"]'),
213+
('obj-1.obj"2', r'["obj-1"]["obj\"2"]'),
214+
],
215+
)
216+
def test_javascript_identifier_path_to_array_notation(text, result):
217+
assert javascript_identifier_path_to_array_notation(text) == result

0 commit comments

Comments
 (0)