在 QGIS 或 Python 中向 GeoJSON 添加唯一的要素 id

fan*_*men 5 python qgis geojson

根据GeoJSON格式规范

“如果某个功能具有常用标识符,则该标识符应作为名称为“id”的功能对象的成员包含在内。”

我的问题是如何将其添加到我的 GeoJSON 中?

如果我将其创建为属性,然后将其保存为 QGIS 中的 GeoJSON,它最终会出现在“属性”而不是“特征”中。

这就是我想做的:

{
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name":"urn:ogc:def:crs:OGC:1.3:CRS84" } },

"features": [
{ "type": "Feature", "id":"1", "properties": { "Namn":.................
Run Code Online (Sandbox Code Playgroud)

这就是 QGIS 产生的结果:

{
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },

"features": [
{ "type": "Feature", "properties": { "id": 1, "Name".................. 
Run Code Online (Sandbox Code Playgroud)

我也尝试过 PyGeoj https://github.com/karimbahgat/PyGeoj。它有一个添加唯一 ID 的功能,但它也会将其添加到属性下。

如果我打开 GeoJSON 并手动写入,那么它可以工作,但我不想对所有图层执行此操作,其中一些图层包含许多功能。

fan*_*men 2

我想我会在这里写下我是如何解决它的,以防其他人遇到同样的问题。

一个简单的Python脚本:

#create empty file to be writen to
file = open("kommun_id.geojson", "w")
count = 0

#read original file
with open('kommun.geojson', 'r')as myfile:
    for line in myfile:

       #lines that don't need to be edited with an 'id'
       if not line.startswith('{ "type": '):
            file.write(line)
       else:
            #lines that need to be edited
            count = count +1
            idNr = str(count)
            file.write(line[0:20] + '"id":'+ '"'+ idNr + '",' +line[21:])

file.close()
Run Code Online (Sandbox Code Playgroud)

它可能不适用于所有 geoGJSON,但它适用于我用 QGIS 创建的那些