如何从 JSON 字典中附加项目并修改其结构以形成 GIS 软件可接受的 geoJSON 字典?

问题描述 投票:0回答:0

所以这似乎是一个基本的 Python 问题,我认为这是在适当的位置放置一些括号的问题,但无论如何我已经挣扎了一段时间但没有成功。

我有许多 JSON 文件,每个文件都包含一系列特征(下例中有 2 个),它们的几何形状和属性以如下格式描述:

{ 
    "version": '1.0',
    "properties": [
        {
            "a":1,
            "b":2,
            "c":3,
            "coordinates": [0, 10]
        },
        {
            "a":4,
            "b":5,
            "c":6,
            "coordinates": [10,20]
        }
    ]
}

现在,geoJSON 已经预定义了它的结构,我想得到这样的输出:

{"type": "FeatureCollection",
"features": [

    {"type":"Feature",
    "properties":{
        "a":1,
        "b":2,
        "c":3,
        "coordinates": [0, 10]
      },
    "geometry":{
        "type":"Point",
        "coordinates":[0,10]}},

    {"type":"Feature",
    "properties":{
        "a":2,
        "b":3,
        "c":4,
        "coordinates": [10, 20]
      },
    "geometry":{
        "type":"Point",
        "coordinates":[10,20]}}
        ]
}

下面的代码完成了这项工作,但是

for loop
在遍历原始 JSON 文件中的对象时,会覆盖前一个而不是附加新功能:

f = open(file)
data = json.load(f)

geojson = {
    'type': 'FeatureCollection',
    'features': [{'type':'Feature',
                 'properties': {},
                  'geometry': {'type': 'Point',
                               'coordinates': []}
                }]
}

for object in data['properties']:
  geojson['features'][0]['properties'] = object
  geojson['features'][0]['geometry']['type'] = 'Point'
  geojson['features'][0]['geometry']['coordinates'] = [object['coordinates'][0], object['coordinates'][1]]

with open(processed_file, 'a') as f:
json.dump(geojson, f, indent=2)

我知道这里有什么问题,但不知道如何解决。如果我在

with open
循环中移动
dump
for
,那么输出的 json 文件将包含两个完全独立的特征,而不是一个只有不同对象在“特征”键中的通用字典。

我感觉很蠢,但真的卡住了。非常感谢您的帮助!

保重,

雅各布

python json dictionary geojson
© www.soinside.com 2019 - 2024. All rights reserved.