如何将 geojson 中的属性定位在所有属性之上?

How to position attribute in geojson on top of all properties?

我正在尝试从属性数组中删除 feature_id 属性 并向上移动。

with open('test.geojson', 'r+') as gjson:
    data = json.load(gjson)
        for l in range(0, len(data['features'])):
            data['features'][l]['id'] = data['features'][l]['properties']['feature_id']
            del data['features'][l]['properties']['feature_id']
        gjson.seek(0)
        json.dump(data, gjson, indent=4)
        gjson.truncate()

这是输入。

{
    "type": "FeatureCollection",
    "name": "name",
    "features": [
        {
            "type": "Feature",
            "properties": {
                "feature_id": "1e181120-2047-4f97-a359-942ef5940da1",
                "type": 1
            },
            "geometry": {
                "type": "Polygon",
                "coordinates": [
                    [...]
                ]
            }
        }
    ]
}

它完成了工作,但在底部添加了 属性

{
    "type": "FeatureCollection",
    "name": "name",
    "features": [
        {
            "type": "Feature",
            "properties": {
                "type": 1
            },
            "geometry": {
                "type": "Polygon",
                "coordinates": [
                    [..]
                ]
            },
            "id": "1e181120-2047-4f97-a359-942ef5940da1"
        }
    ]
}

如您所见,最后添加了 id,但它应该位于 properties 之前。

您可以使用 OrderedDict

with open('test.geojson', 'r+') as gjson:
    data = json.load(gjson, object_pairs_hook=OrderedDict)
    for l in range(0, len(data['features'])):
        d = data['features'][l]
        d['id'] = data['features'][l]['properties']['feature_id']
        d.move_to_end('id', last=False)         
        del d['properties']['feature_id']

    gjson.seek(0)
    json.dump(data, gjson, indent=4)
    gjson.truncate()