1

I'm writing a Python script to convert shapefiles into GeoJSONs but I would like to remove many of the fields as they are redundant and rename the ones I am retaining.

Here's an extract of where I have got to so far.

ef convert_shape_to_geojson(indir, in_shape, in_projection):
    inShapefile = in_shape
    inDriver = ogr.GetDriverByName("ESRI Shapefile")
    inDataSource = inDriver.Open(inShapefile, 0)
    inLayer = inDataSource.GetLayer()


    outGeoSJON = 'output.geojson'
    outfile = os.path.join(indir, outGeoSJON)
    driver = ogr.GetDriverByName("GeoJSON")
    if os.path.exists(outfile):
        driver.DeleteDataSource(outfile)
    data_source = driver.CreateDataSource(outGeoSJON)

    srs = osr.SpatialReference()
    srs.ImportFromEPSG(in_projection)

    out_layer = data_source.CreateLayer(outGeoSJON.split(".", 0), srs, geom_type=ogr.wkbMultiPolygon)

I've created new shapefiles in the past with brand new fields like so:

field_parcel = ogr.FieldDefn("PARCEL",ogr.OFTString)
field_parcel.SetWidth(20)
out_layer.CreateField(field_parcel)
out_layer.CreateField(ogr.FieldDefn("X",ogr.OFTInteger))
out_layer.CreateField(ogr.FieldDefn("Y",ogr.OFTInteger))
out_layer.CreateField(ogr.FieldDefn("BUFFDIS",ogr.OFTReal))

But I have no clue at the moment how to take existing field definitions from a source file but renaming the fields whilst also carrying over the source attributes.

Is anyone able to help out or point me to some further reading?

2

1 Answer 1

1

So following on from user30184's suggestion. I've used ogr2ogr and subprocess in my script. Here's an extract:

convert_command = ['ogr2ogr',
                   '-f', 'GeoJSON',
                   '-sql',
                   'SELECT field_1 AS alias_1, field_4 AS alias_2 FROM layername',
                   '/home/converted.geojson',
                   '/home/layername.shp']

subprocess.check_call(convert_command)

This did everything I needed and it was quick to set up.

Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.