From a87e3821ce052ade13eea9f42e52ff480d7c7622 Mon Sep 17 00:00:00 2001 From: Syed Huzaifa Rahman Date: Tue, 17 Nov 2026 11:51:36 +0500 Subject: [PATCH] Load TopoJson data given as a string or filename TopoJson documents that data can be a str, but a TopoJSON string or a filename was kept as-is and rendering failed with AttributeError: 'str' object has no attribute 'get'. Load the string the same way GeoJson does: parse inline JSON, fetch URLs and read files. --- folium/features.py | 14 ++++++++++++-- tests/test_features.py | 19 +++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/folium/features.py b/folium/features.py index 136f5e652b..1cc24fddbf 100644 --- a/folium/features.py +++ b/folium/features.py @@ -951,7 +951,8 @@ class TopoJson(JSCSSMixin, Layer): embedded in Leaflet's JavaScript. * If dict, then data will be converted to JSON and embedded in the JavaScript. - * If str, then data will be passed to the JavaScript as-is. + * If str, it can be a TopoJSON string, a URL or a path to a file. + The data will be loaded and embedded in the JavaScript. object_path: str The path of the desired object into the TopoJson structure. @@ -981,7 +982,7 @@ class TopoJson(JSCSSMixin, Layer): -------- >>> # Providing file that shall be embedded. >>> TopoJson(open("foo.json"), "object.myobject") - >>> # Providing filename that shall not be embedded. + >>> # Providing filename. >>> TopoJson("foo.json", "object.myobject") >>> # Providing dict. >>> TopoJson(json.load(open("foo.json")), "object.myobject") @@ -1047,6 +1048,15 @@ def __init__( elif type(data) is dict: self.embed = True self.data = data + elif isinstance(data, str): + self.embed = True + if data.lower().startswith(("http:", "ftp:", "https:")): + self.data = requests.get(data).json() + elif data.lstrip()[:1] == "{": + self.data = json.loads(data) + else: + with open(data, "rb") as f: + self.data = json.load(f) else: self.embed = False self.data = data diff --git a/tests/test_features.py b/tests/test_features.py index 5f2ae7b37c..4e4d17549d 100644 --- a/tests/test_features.py +++ b/tests/test_features.py @@ -113,6 +113,25 @@ def test_topojson_popup(popup): assert f"{topojson.get_name()}.bindPopup(" in map_.get_root().render() +@pytest.mark.parametrize("as_filename", [False, True]) +def test_topojson_from_str(as_filename): + """TopoJson accepts a TopoJSON string or a filename, as documented.""" + path = os.path.join(os.path.dirname(__file__), "or_counties_topo.json") + if as_filename: + data = path + else: + with open(path) as f: + data = f.read() + + map_ = folium.Map() + topojson = folium.TopoJson(data, "objects.or_counties_geo").add_to(map_) + map_.get_root().render() + + assert isinstance(topojson.data, dict) + assert topojson.data["type"] == "Topology" + assert topojson.get_bounds() is not None + + @pytest.mark.parametrize("detail_type", [folium.GeoJsonPopup, folium.GeoJsonTooltip]) @pytest.mark.parametrize( "properties, fields",