如何将geojson中的属性置于所有属性之上?

2024-09-28 01:30:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从属性数组中删除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之前位于顶部


Tags: nameidjsondata属性typepropertiesfeature
1条回答
网友
1楼 · 发布于 2024-09-28 01:30:40

你可以用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()

相关问题 更多 >

    热门问题