向 geojson 文件中的嵌套字典添加新键/值

时间:2021-03-02 13:25:42

标签: python json python-3.x geojson

我有一个 .js 文件,其中包含用于在地图上绘制点的数据。在文件中,我有一个包含嵌套字典的单行 var 语句。

var json_Project = {"type":"FeatureCollection","name":"project","crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:OGC:1.3:CRS84"}},"features":[{"type":"Feature","properties":{"ID":"001","field1":"someText","field2":"someText"},"geometry":{"type":"Point","coordinates":[-1.14,60.15]}},{"type":"Feature","properties":{"ID":"002","field1":"someText","field2":"someText"},"geometry":{"type":"Point","coordinates":[-1.14,60.15]}}]}

其中一个包含 "features" 键,用于存储每个点的字典列表(请参见下文以提高可读性)。

var json_Project = {"type":"FeatureCollection","name":"project","crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:OGC:1.3:CRS84"}},"features":[
{"type":"Feature","properties":{"ID":"001","field1":"someText","field2":"someText"},"geometry":{"type":"Point","coordinates":[-1.14,60.15]}},
{"type":"Feature","properties":{"ID":"002","field1":"someText","field2":"someText"},"geometry":{"type":"Point","coordinates":[-1.14,60.15]}}]}

第一个点的"properties""ID":"001",第二个点有"ID":"001"

我想用 "INFORMATION:" 为每个点插入一个新属性,并使用 "ID" 中的键从另一个字典中获取值。

info_dict = {'001': 'This is Project 1', 
             '002': 'This is Project 2'}

具体来说,我希望在 "field2" 之前插入这个新属性,使其看起来像:

var json_Project = {"type":"FeatureCollection","name":"project","crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:OGC:1.3:CRS84"}},"features":[
{"type":"Feature","properties":{"ID":"001","field1":"someText","INFORMATION":"This is Project 1","field2":"someText"},"geometry":{"type":"Point","coordinates":[-1.14,60.15]}},
{"type":"Feature","properties":{"ID":"002","field1":"someText","INFORMATION":"This is Project 2","field2":"someText"},"geometry":{"type":"Point","coordinates":[-1.14,60.15]}}]}

我徒劳的尝试涉及将单行转换为字符串,然后提取 "features:" 字符串之后的所有内容,因为它在文件中是唯一的。但不确定如何添加新的键/值对。

with open('project.js') as f:
    contents = f.read().split()
    contents_toString = ''.join(contents)
    new_contents = re.findall('(?<="features":\[).*$', contents_toString)

编辑

感谢@TenaciousB,我可以读取geojson 文件并使用字典中的正确值添加"INFORMATION" 属性:

with open('project.js') as f:
    contents = f.read()
    x = json.loads(contents)
    for y in x['features']:
        key = y['properties']['ID']
        description = dictionary[key]
        y['properties']['INFORMATION'] = description

我仍然不确定如何:

  1. 在读取之前以编程方式删除 var json_Project =
  2. "INFORMATION" 属性放在 "field2" 之前;
  3. 重新插入 var json_Project = ,保存并确保保留单行格式。

0 个答案:

没有答案