首页 > 解决方案 > Python 更新 geojson 属性

问题描述

我有一个包含很多特征的 geojson 特征集合数据集。我想使用 json 文件的属性添加/更新每个功能的属性。两个数据集的唯一标识符是“uuid”值。

这是geojson格式:

mtx = {
        "type": "FeatureCollection",
        "crs": {
            "type": "name",
            "properties": {
                "name": "EPSG:4326"
            }
        },
        "features": [
            {
                "type": "Feature",
                "id": 1,
                "geometry": {
                    "type": "Point",
                    "coordinates": [
                        5.36516933279853,
                        51.5510854507331
                    ]
                },
                "properties": {
                    "OBJECTID": 1,
                    "PK_UID": 1,
                    "uuid": "1efa8916-c854-465b-80f5-1f02fd25fb31",
                    "road": "A2",
                    "lane": 1,
                    "km": 134.96,
                    "bearing": 148.02261,
                    "locid": "A2134.96"
                }
            },
            {
                "type": "Feature",
                "id": 2,
                "geometry": {
                    "type": "Point",
                    "coordinates": [
                        5.05380200345974,
                        52.3264095459638
                    ]
                },
                "properties": {
                    "OBJECTID": 2,
                    "PK_UID": 2,
                    "uuid": "73bf3758-6754-433f-9896-d03c0673ae55",
                    "road": "A1",
                    "lane": 3,
                    "km": 11.593,
                    "bearing": 113.404253,
                    "locid": "A111.593"
                }
            }
        ]
    }

这是json格式:

msi= [
        {
            "uuid": "1efa8916-c854-465b-80f5-1f02fd25fb31",
            "road": "A2",
            "carriageway": "R",
            "lane": "1",
            "km": "134.960",
            "display": "blank",
            "display_attrs": "{'flashing': 'false'}",
            "speedlimit": "null"
        },
        {
            "uuid": "73bf3758-6754-433f-9896-d03c0673ae55",
            "road": "A1",
            "carriageway": "R",
            "lane": "3",
            "km": "11.593",
            "display": "blank",
            "display_attrs": "{'flashing': 'false'}",
            "speedlimit": "null"
        }
    ]

那么如何制作一个循环遍历geojson功能并根据“uuid”值使用来自json的匹配属性更新每个功能属性的python脚本呢?

我尝试了这样的事情,但这并没有给我预期的结果:

#Loop over GeoJSON features and update the new properties from msi json
for feat in mtx['features']:
    for i in range(len(msi)):
        if mtx['features'][i]['properties']['uuid'] == msi[i]['uuid']:
            feat ['properties'].update(msi[i])

谢谢你的协助。

标签: pythongeojson

解决方案


我会做这样的事情(完全未经测试,所以要小心错误......):

# Turn msi into a dictionary for easy access
msi_dict = {m['uuid']: m for m in msi}

for f in mtx['features']:
    f['properties'].update(msi_dict.get(f['properties']['uuid'], {}))

推荐阅读