jazzband / geojson

Python bindings and utilities for GeoJSON
https://pypi.python.org/pypi/geojson/
BSD 3-Clause "New" or "Revised" License
905 stars 120 forks source link

Included JSON encoder can't handle Decimal #86

Closed crccheck closed 7 years ago

crccheck commented 7 years ago

Example

from geojson import Point
print(Point((Decimal('0'), Decimal('0'))))
TypeError: Decimal('0') is not JSON serializable

Expected behavior:

from geojson import Point
print(Point((Decimal('0'), Decimal('0'))))
{"coordinates": ["0", "0"], "type": "Point"}

Workaround

json.dumps(Point((Decimal('0'), Decimal('0'))), cls=AnotherJSONEncoder)
frewsxcv commented 7 years ago

Serializing Decimals also doesn't work for Python's built-in JSON encoder. For some people, it makes sense to encode Decimals as JSON floats and for others it makes sense to encode as strings. I'm leaning towards suggesting what was said in https://github.com/frewsxcv/python-geojson/issues/49 and make your own encoder to treat Decimal however you want it to be treated.

crccheck commented 7 years ago

Yeah, I didn't test it, but I'm afraid that going to float then JSON would change the precision of the numbers. That's happened to me in the past. Since precision is important for lat/lng, and I know Django's JSONEncoder works with decimal, I opted to stay in Decimal as long as possible.

frewsxcv commented 7 years ago

I'd recommend subclassing python-geojson's encoder and adding in the appropriate logic to encode Decimals.

frewsxcv commented 7 years ago

If you need help with any of that, let me know.