From bd4e7c8c6eba2ab1c7c80730ac474de456a9d86b Mon Sep 17 00:00:00 2001 From: Jacek Bylina Date: Tue, 3 Dec 2024 17:18:07 +0100 Subject: [PATCH] Don't fail on mixed typed JSONField --- fiona/ogrext.pyx | 5 ++++- tests/test_geojson.py | 26 ++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/fiona/ogrext.pyx b/fiona/ogrext.pyx index 8ae7f799e..ec331a9ce 100644 --- a/fiona/ogrext.pyx +++ b/fiona/ogrext.pyx @@ -387,7 +387,10 @@ cdef class JSONField(AbstractField): cdef object get(self, OGRFeatureH feature, int i, object kwds): val = OGR_F_GetFieldAsString(feature, i) - return json.loads(val) + try: + return json.loads(val) + except json.JSONDecodeError: + return val cdef set(self, OGRFeatureH feature, int i, object value, object kwds): value_b = json.dumps(value).encode("utf-8") diff --git a/tests/test_geojson.py b/tests/test_geojson.py index c20f525db..e5b34a4db 100644 --- a/tests/test_geojson.py +++ b/tests/test_geojson.py @@ -164,3 +164,29 @@ def test_empty_array_property(tmp_path): ) ) list(fiona.open(tmp_path.joinpath("test.geojson"))) + +def test_json_field_property_with_mixed_types(tmp_path): + """Confirm fix for bug reported in gh-1470.""" + features = [ + { + "type": "Feature", + "properties": {"array_prop": []}, + "geometry": {"type": "Point", "coordinates": [12, 24]}, + }, + { + "type": "Feature", + "properties": {"array_prop": "a"}, + "geometry": {"type": "Point", "coordinates": [12, 24]}, + } + ] + for idx, f in enumerate([features, list(reversed(features))]): + fname = f"test_{idx}.geojson" + tmp_path.joinpath(fname).write_text( + json.dumps( + { + "type": "FeatureCollection", + "features": f, + } + ) + ) + list(fiona.open(tmp_path.joinpath(fname)))