Newsletter
TechAnV Blog
Get updates on security engineering, Rust, eBPF, and DevSecOps. No spam, unsubscribe anytime.
Check your inbox and click the confirmation link to complete your subscription.
Outputting JSON with reduced floating point precision#
datasette-leaflet-geojson outputs GeoJSON geometries in HTML pages in a way that can be picked up by JavaScript and used to plot a Leaflet map.
These geometries often look something like this:
1{2 "type":"MultiPolygon",3 "coordinates":[[[[-122.4457678900319,37.77292891669105],[-122.441075063058,37.77352490695095]...Decimal_degrees: Precision on Wikipedia says that 0.00001 should be accurate to within around a meter.
Shortening these floating point representations can shave 100KB+ off an HTML page with a lot of GeoJSON shapes on it!
There’s a lengthy Stack Overflow about this but it’s difficult to follow because ways of doing this changed between Python 2 and Python 3. Here’s what worked for me:
1def round_floats(o):2 if isinstance(o, float):3 return round(o, 5)4 if isinstance(o, dict):5 return {k: round_floats(v) for k, v in o.items()}6 if isinstance(o, (list, tuple)):7 return [round_floats(x) for x in o]8 return o9
10data = json.dumps(round_floats(data))See issue 11 for details.