Created
July 5, 2020 23:10
-
-
Save mapmeld/fb8fb16e20209aef3fcfeaaacb1bbfa3 to your computer and use it in GitHub Desktop.
Add JSON block data to a shapefile with GDAL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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