Created
February 28, 2019 21:08
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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