Skip to content

Commit

Permalink
Don't fail on mixed typed JSONField
Browse files Browse the repository at this point in the history
  • Loading branch information
jbylina committed Dec 3, 2024
1 parent c4d6431 commit 382d2ab
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
5 changes: 4 additions & 1 deletion fiona/ogrext.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
26 changes: 26 additions & 0 deletions tests/test_geojson.py
Original file line number Diff line number Diff line change
Expand Up @@ -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-xxxx."""
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)))

0 comments on commit 382d2ab

Please sign in to comment.