Skip to content

Instantly share code, notes, and snippets.

@bdw
Created April 12, 2016 10:03
Show Gist options
  • Save bdw/6362152b96c30dbe247b46f1cd15ee0f to your computer and use it in GitHub Desktop.
Save bdw/6362152b96c30dbe247b46f1cd15ee0f to your computer and use it in GitHub Desktop.
geojson to postgis
#!/usr/bin/env python
from __future__ import print_function, unicode_literals
import operator
import psycopg2
import psycopg2.extras
import io
import json
import sys
import logging
'''
CREATE EXTENSION hstore;
CREATE EXTENSION postgis;
CREATE TABLE features (
id integer not null,
geom geometry(geometry, 4326),
properties hstore
);
'''
INSERT_STATEMENT = 'INSERT INTO features (id, geom, properties) VALUES (%s, ST_SetSRID(ST_GeomFromGeoJSON(%s), 4326), %s);'
def import_feature(cur,feature_data):
if feature_data.get('type') == 'FeatureCollection':
for feature in feature_data['features']:
import_feature(cur, feature)
elif feature_data.get('type') == 'Feature':
geojson = json.dumps(feature_data['geometry'])
str_dict = dict((unicode(k), unicode(v)) for k, v in feature_data['properties'].items())
cur.execute(INSERT_STATEMENT, (feature_data['id'], geojson, str_dict))
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
con = psycopg2.connect('')
# use hstore to log data
psycopg2.extras.register_hstore(con)
# truncate features table
with con:
with con.cursor() as cur:
cur.execute('truncate features;')
if len(sys.argv) == 1:
handles = [sys.stdin]
else:
handles = [io.open(a,'r') for a in sys.argv[1:]]
for handle in handles:
with handle:
feature_data = json.load(handle)
with con:
with con.cursor() as cur:
import_feature(cur, feature_data)
con.commit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment