Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 2 additions & 6 deletions fiona/ogrext.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -412,14 +412,10 @@ cdef class JSONField(AbstractField):
key = key_b.decode("utf-8")
val = OGR_F_GetFieldAsString(feature, i)

# String(JSON) is the fallback for GDAL in the case of
# properties that are a mix of strings and numbers. See gh-1451.
# In GDAL 3.11, users will be able to override this and declare
# a field type.
try:
return json.loads(val)
except json.JSONDecodeError as error:
raise FieldError(f"String(JSON) field could not be decoded: {val=}, {error=}")
except json.JSONDecodeError:
return val
Comment on lines +417 to +418

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
except json.JSONDecodeError:
return val
except json.JSONDecodeError as error:
warnings.warn(f"JSON field value not decoded, returning as string: {val=}, {error=}", FeatureWarning)
log.info("JSON field value not decoded, returning as string: val=%r, error=%r", val, error)
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-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)))