如何将JSON字典转换为GIS兼容GeoJSON并解决元素覆盖问题
JSON转GeoJSON:Feature覆盖问题解决
原输入JSON结构
{ "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":4, "b":5, "c":6, "coordinates": [10, 20] }, "geometry":{ "type":"Point", "coordinates":[10,20]}} ] }
问题代码
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)
问题原因
你的代码里geojson['features']初始只创建了一个Feature对象,循环时每次都修改这个唯一的对象,后面的属性直接覆盖前面的,最终只会保留最后一个Feature。如果把写入逻辑放进循环,又会生成多个独立的FeatureCollection,不符合要求。
修正后的代码
单文件处理
import json # 替换为你的输入文件路径 input_file = "input.json" # 替换为你的输出文件路径 output_file = "output.geojson" with open(input_file, 'r', encoding='utf-8') as f: data = json.load(f) # 初始化FeatureCollection,features设为空列表 geojson = { 'type': 'FeatureCollection', 'features': [] } # 遍历每个属性对象,生成独立的Feature for prop in data['properties']: feature = { 'type': 'Feature', 'properties': prop, # 直接复用原属性(包含coordinates) 'geometry': { 'type': 'Point', 'coordinates': prop['coordinates'] # 提取坐标作为几何信息 } } # 将新Feature添加到features列表 geojson['features'].append(feature) # 一次性写入完整的GeoJSON with open(output_file, 'w', encoding='utf-8') as f: json.dump(geojson, f, indent=2)
多文件批量处理
如果要处理多个JSON文件,可以用glob模块批量遍历:
import json import glob # 匹配所有json文件(可根据需求修改路径) input_files = glob.glob("*.json") for file_path in input_files: # 输出文件名:原文件名替换为geojson output_file = file_path.replace(".json", ".geojson") with open(file_path, 'r', encoding='utf-8') as f: data = json.load(f) geojson = { 'type': 'FeatureCollection', 'features': [] } for prop in data['properties']: feature = { 'type': 'Feature', 'properties': prop, 'geometry': { 'type': 'Point', 'coordinates': prop['coordinates'] } } geojson['features'].append(feature) with open(output_file, 'w', encoding='utf-8') as f: json.dump(geojson, f, indent=2)
关键修改点
- 初始化
geojson['features']为空列表,而不是预先放入一个Feature对象 - 循环中每次创建新的Feature字典,而不是修改同一个对象
- 把每个新生成的Feature通过
append()添加到features列表,保证所有Feature都被保留 - 最后一次性将完整的FeatureCollection写入文件,确保结构正确
内容的提问来源于stack exchange,提问作者Guziko
相关产品推荐
相关产品推荐

