首页 > 解决方案 > 如何将geojson中的属性置于所有属性之上?

问题描述

我正在尝试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

标签: pythonjsongeojson

解决方案


您可以为此使用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()

推荐阅读