Skip to content

Instantly share code, notes, and snippets.

@Stimim
Created May 18, 2021 14:29
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 Stimim/d115cc7c0ac6db416be22a618cff1cba to your computer and use it in GitHub Desktop.
Save Stimim/d115cc7c0ac6db416be22a618cff1cba to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import argparse
import csv
import json
def ConvertGeoJsonToWebsiteFormat(geojson):
if geojson.get('type') != 'FeatureCollection':
return []
features = geojson.get('features', [])
return_value = []
for feature in features:
if feature.get('type') != 'Feature':
continue
geometry = feature.get('geometry', {})
if not geometry:
continue
properties = feature.get('properties', {})
name = properties.get('name')
if not name:
continue
source = properties.get('資料來源')
if not source:
print(name)
continue
begin = properties.get('begin', None)
end = properties.get('end', None)
try:
if not begin or not end or not (begin < end):
print(f'invalid feature: {feature}')
continue
except Exception:
print(f'invalid feature: {feature}')
continue
return_value.append(feature)
return return_value
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--input', '-i', default='input.csv')
parser.add_argument('--output', '-o', default='output.geojson')
args = parser.parse_args()
with open(args.input) as csvfile:
reader = csv.reader(csvfile)
headers = next(reader)
# print(headers)
all_features = []
for row in reader:
d = dict(zip(headers,row))
geojson_string = d.get('GeoJSON', '')
if not geojson_string:
continue
geojson = json.loads(geojson_string)
converted_data = ConvertGeoJsonToWebsiteFormat(geojson)
if not converted_data:
continue
all_features += converted_data
print(f'Dumping {len(all_features)} records')
with open(args.output, 'w') as f:
o = {
'type': 'FeatureCollection',
'features': all_features,
}
json.dump(o, f, indent=2, sort_keys=True)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment