Skip to content

Instantly share code, notes, and snippets.

@danvk
Created February 28, 2019 21:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danvk/ec958c35b7e26de0de27aff96420bc2e to your computer and use it in GitHub Desktop.
Save danvk/ec958c35b7e26de0de27aff96420bc2e to your computer and use it in GitHub Desktop.
Pretty-print GeoJSON in a slightly more compact way by putting coordinates on one line.
#!/usr/bin/env python3
"""Pretty-print GeoJSON in a slightly more compact way by putting coordinates on one line.
Compare:
[
[
37.23423,
79.23423
],
[
37.24434,
80.01234
]
]
vs.
[
[ 37.23423, 79.23423 ],
[ 37.24434, 80.01234 ]
]
"""
import json
import sys
# See https://stackoverflow.com/a/26512016/388951
class CompactJSONEncoder(json.JSONEncoder):
def __init__(self, *args, **kwargs):
super(CompactJSONEncoder, self).__init__(*args, **kwargs)
self.current_indent = 0
self.current_indent_str = ''
def encode(self, o):
# Special Processing for lists
if isinstance(o, (list, tuple)):
primitives_only = True
for item in o:
if isinstance(item, (list, tuple, dict)):
primitives_only = False
break
output = []
if primitives_only:
for item in o:
output.append(json.dumps(item))
return '[ ' + ', '.join(output) + ' ]'
else:
self.current_indent += self.indent
self.current_indent_str = ''.join([' ' for x in range(self.current_indent)])
for item in o:
output.append(self.current_indent_str + self.encode(item))
self.current_indent -= self.indent
self.current_indent_str = ''.join([' ' for x in range(self.current_indent)])
return '[\n' + ',\n'.join(output) + '\n' + self.current_indent_str + ']'
elif isinstance(o, dict):
output = []
self.current_indent += self.indent
self.current_indent_str = ''.join([' ' for x in range(self.current_indent)])
for key, value in o.items():
output.append(
self.current_indent_str + json.dumps(key) + ': ' + self.encode(value)
)
self.current_indent -= self.indent
self.current_indent_str = ''.join([' ' for x in range(self.current_indent)])
return '{\n' + ',\n'.join(output) + '\n' + self.current_indent_str + '}'
else:
return json.dumps(o)
if __name__ == '__main__':
if len(sys.argv) == 1:
geojson = json.load(sys.stdin)
else:
with open(sys.argv[1]) as f:
geojson = json.load(f)
print(CompactJSONEncoder(indent=2).encode(geojson))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment