Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add JSON block data to a shapefile with GDAL
# pip install gdal
import json
from osgeo import ogr
# depends on your shapefile
target_shapefile = 'tl_2010_sample_shapefile.shp'
fips_id = 'GEOID10'
saveblocks = json.loads(open('savefile.json', 'r').read())
driver = ogr.GetDriverByName('ESRI Shapefile')
dataSource = driver.Open(target_shapefile, 1)
layer = dataSource.GetLayer()
for item in saveblocks.keys():
fields = saveblocks[item].keys()
break
# caution: running twice will create COLNAME, COLNAME_1, COLNAME_2
# a long column name may be cut a shorter one
print('creating columns')
for field in fields:
fldDef = ogr.FieldDefn(field, ogr.OFTInteger)
layer.CreateField(fldDef)
print('setting columns')
feature = layer.GetNextFeature()
while feature:
geoid = feature.GetField(fips_id)
if geoid in saveblocks:
for field in fields:
feature.SetField(field, saveblocks[geoid][field])
layer.SetFeature(feature)
feature = layer.GetNextFeature()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.