Skip to content

Instantly share code, notes, and snippets.

@mapmeld
Created July 5, 2020 23:10
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 mapmeld/fb8fb16e20209aef3fcfeaaacb1bbfa3 to your computer and use it in GitHub Desktop.
Save mapmeld/fb8fb16e20209aef3fcfeaaacb1bbfa3 to your computer and use it in GitHub Desktop.
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