5

I run processing.run("native:buffer") and from newly created vector I get all features and export them to string using QgsJsonExporter().

My problem is that newly created vector gives new IDs to all features and they aren't equal to attribute ID's values. And after exporting them to GeoJSON using QgsJsonExporter() I get GeoJSON features with identifiers.

However I can solve this by declaring processing.run("native:buffer") algorithm OUTPUT to .geosjon file and opening it afterwards.

Is there a way that I can get GeoJSON string without IDs without having to save OUTPUT to .geojson and reading it to string afterwards.

vl = QgsVectorLayer(sys.argv[1],"mygeojson","ogr")

def runProcessingNativeBuffer(inputGeoJson, distance):
    processing.algorithmHelp("native:buffer")
    return processing.run("native:buffer",
                         {'INPUT': inputGeoJson,
                          'DISTANCE': distance, 'SEGMENTS': 5,
                          'END_CAP_STYLE': 0, 'JOIN_STYLE': 0,
                          'MITER_LIMIT': 2, 'DISSOLVE': False,
                          'OUTPUT': "TEMPORARY_OUTPUT"})

ats = runProcessingNativeBuffer(vl, sys.argv[2])

vl1=ats['OUTPUT']

features = vl1.getFeatures()
exporter = QgsJsonExporter()
print("GEOJSON",exporter.exportFeatures(features))

IDs in properties are fine I don't need additional IDs in "features"

IDs in "properties" are fine I don't need additional IDs in "features"

1 Answer 1

3

No chance to export features without id unless you manually remove it from dictionary using some code. But using exportFeature instead of exportFeatures, you can assign id value in properties to upper id like this:

{
  "features":[
     { "geometry": { ... },
       "id": 25,
       "properties": { "id": 25,
                        ...

Sample script:

layer = iface.activeLayer()
features = layer.getFeatures()

exporter = QgsJsonExporter()

### Lines you need ###
json_string = '{"features":['

# set id parameter to f["id"]. id is paramater and "id" is the field name in attribute table
json_string += ','.join([exporter.exportFeature(f, id=f["id"]) for f in features])
json_string += '], "type": "FeatureCollection"} ' 
######################

print(json_string)

Sample result:

{
    "features": [{
        "geometry": { ... },
        "id": 20,
        "properties": {
            "id": 20,
            "namas": "foo"
        },
        "type": "Feature"
    }, {
        "geometry": { ... },
        "id": 25,
        "properties": {
            "id": 25,
            "namas": "bar"
        },
        "type": "Feature"
    }],
    "type": "FeatureCollection"
}
1
  • The result is string. I changed its format to make it look more beautiful. Commented Sep 16, 2020 at 12:37

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.