Skip to content

Instantly share code, notes, and snippets.

@henriklied
Created February 1, 2022 12:06
Show Gist options
  • Save henriklied/1c8e7966f8fcaa0679890b9533841738 to your computer and use it in GitHub Desktop.
Save henriklied/1c8e7966f8fcaa0679890b9533841738 to your computer and use it in GitHub Desktop.
Quick script to convert an unnested json file with points to a valid geojson file
#!/usr/bin/env python
import json
import argparse
def parse_json(f):
geojson = {}
features = []
geojson['type'] = 'FeatureCollection'
j = json.load(open(f))
geo_keys = {}
lat_key = None
lng_key = None
geo_keys['lat'] = 'lat latitude Latitude LATITUDE LAT Lat'.split(" ")
geo_keys['lng'] = 'lon long lng longitude Lon LON Long LONG Lng LNG Longitude LONGITUDE'.split(" ")
for obj in j:
feature = {}
properties = {}
feature['type'] = 'Feature'
for k,v in obj.items():
if k in geo_keys['lat']:
lat_key = k
if k in geo_keys['lng']:
lng_key = k
properties[k] = v
feature['properties'] = properties
feature['geometry'] = {
'type':'Point',
'coordinates':[ obj[lng_key], obj[lat_key] ]
}
features.append(feature)
geojson['features'] = features
return geojson
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Convert (unnested) JSON file to geojson')
parser.add_argument('--infile', dest='infile')
parser.add_argument('--outfile', dest='outfile')
args = parser.parse_args()
res = parse_json(args.infile)
with open(args.outfile, 'w') as fp:
fp.write(json.dumps(res, indent=4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment