Skip to content

Commit

Permalink
Fix topojson invalid object path (#1665)
Browse files Browse the repository at this point in the history
* Fix Topojson object path

* add tests

* Fix test
  • Loading branch information
Conengmo committed Nov 27, 2022
1 parent 0b05071 commit 762c876
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
6 changes: 5 additions & 1 deletion folium/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
get_bounds,
get_obj_in_upper_tree,
image_to_url,
javascript_identifier_path_to_array_notation,
none_max,
none_min,
parse_options,
Expand Down Expand Up @@ -901,7 +902,7 @@ class TopoJson(JSCSSMixin, Layer):
var {{ this.get_name() }} = L.geoJson(
topojson.feature(
{{ this.get_name() }}_data,
{{ this.get_name() }}_data.{{ this.object_path }}
{{ this.get_name() }}_data{{ this._safe_object_path }}
),
{
{%- if this.smooth_factor is not none %}
Expand Down Expand Up @@ -949,6 +950,9 @@ def __init__(
self.data = data

self.object_path = object_path
self._safe_object_path = javascript_identifier_path_to_array_notation(
object_path
)

if style_function is None:

Expand Down
9 changes: 9 additions & 0 deletions folium/utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -493,3 +493,12 @@ def parse_options(**kwargs):
def escape_backticks(text):
"""Escape backticks so text can be used in a JS template."""
return re.sub(r"(?<!\\)`", r"\`", text)


def escape_double_quotes(text):
return text.replace('"', r"\"")


def javascript_identifier_path_to_array_notation(path):
"""Convert a path like obj1.obj2 to array notation: ["obj1"]["obj2"]."""
return "".join(f'["{escape_double_quotes(x)}"]' for x in path.split("."))
26 changes: 26 additions & 0 deletions tests/test_utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@
_is_url,
camelize,
deep_copy,
escape_double_quotes,
get_obj_in_upper_tree,
if_pandas_df_convert_to_numpy,
javascript_identifier_path_to_array_notation,
parse_options,
validate_location,
validate_locations,
Expand Down Expand Up @@ -189,3 +191,27 @@ def test_parse_options():
)
def test_is_url(url):
assert _is_url(url) is True


@pytest.mark.parametrize(
"text,result",
[
("bla", "bla"),
('bla"bla', r"bla\"bla"),
('"bla"bla"', r"\"bla\"bla\""),
],
)
def test_escape_double_quotes(text, result):
assert escape_double_quotes(text) == result


@pytest.mark.parametrize(
"text,result",
[
("bla", '["bla"]'),
("obj-1.obj2", '["obj-1"]["obj2"]'),
('obj-1.obj"2', r'["obj-1"]["obj\"2"]'),
],
)
def test_javascript_identifier_path_to_array_notation(text, result):
assert javascript_identifier_path_to_array_notation(text) == result

0 comments on commit 762c876

Please sign in to comment.