3

Im trying to convert OGR geodata from one driver to another, like the command line tool ogr2ogr do, but using the python API. My problem is, that the NULL values in the input data are converted as "None" string in the output data.

The Ogr SetField method:

output_feature.SetField('linetype',None)

does not set the attribute 'linetype' = None (or null) in the output feature, as expected, but "None" as string. I tested this with PostgreSQL and GeoJson driver, but probably affected all drivers.

Complete code sample from here:

outDriver = ogr.GetDriverByName("GeoJson")
outDataSource = outDriver.CreateDataSource('test.geojson')
outLayer = outDataSource.CreateLayer("test_layer")

# Add an name field
idField = ogr.FieldDefn("name", ogr.OFTString)
outLayer.CreateField(idField)

point = ogr.Geometry(ogr.wkbPoint)
point.AddPoint(1198054.34, 648493.09)

# Create the feature and set values
featureDefn = outLayer.GetLayerDefn()

#feature 1
feature_1 = ogr.Feature(featureDefn)
feature_1.SetGeometry(point)
feature_1.SetField("name", 'name_1')
outLayer.CreateFeature(feature_1)

#feature 2, name attribute should be NULL but is saved as "None" (string)
feature_2 = ogr.Feature(featureDefn)
feature_2.SetGeometry(point)
feature_2.SetField("name", None)
outLayer.CreateFeature(feature_2)

# Close DataSource
outDataSource.Destroy()
  • 3
    I suppose that for setting field to null you should use OGRFeature::UnsetField. – user30184 Jan 26 '15 at 10:06
1

I had the same issue. My solution was to test if the value is None before using the SetField() method. This avoids going back and forth to set and unset the value.

        field_value = in_feature.GetField(self.fields_name[x])
        if not field_value == None :
            out_feature.SetField(self.fields_name[x], in_feature.GetField(self.fields_name[x]))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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