如何编写Python脚本实现JSON转GeoJSON?求正确指引
编写Python脚本将JSON转换为GeoJSON的正确方向
先明确你之前尝试的问题所在
Copilot生成脚本失效原因:
该脚本默认输入JSON的每个条目都包含geometry和properties字段,但绝大多数普通业务JSON不会按GeoJSON的结构存储地理数据(比如用单独的经纬度字段、WKT字符串等),直接套用自然无效。手动编写GeoJSON的错误:
- GeoJSON对大小写敏感,Feature的类型必须是大写的
"Feature",你写的"feature"不符合规范 - WKT字段不应放在Feature的顶级层级,需归入
properties中 - MultiPoint类型的坐标格式错误,正确格式应为
[[经度1, 纬度1], [经度2, 纬度2]],单个点应使用Point类型
- GeoJSON对大小写敏感,Feature的类型必须是大写的
Docker+jq方案的WSL错误:
属于环境配置问题,暂时可以跳过,优先用Python方案解决核心转换需求。
正确的Python脚本编写步骤
1. 先理清你的原始JSON结构
必须先明确原始JSON中地理数据的存储形式:
- 是单独的
lon/lat字段? - 是WKT格式的字符串?
- 还是其他自定义格式?
2. 选择合适的工具库
- 若涉及WKT解析,使用
shapely库(需先安装:pip install shapely) - 仅处理经纬度字段的话,无需额外库,直接构造GeoJSON结构即可
3. 严格遵循GeoJSON规范
核心结构要求:
- 顶级是
FeatureCollection类型,包含features数组 - 每个
Feature必须包含type(值为"Feature")、geometry(符合GeoJSON几何类型规范)、properties(存储非地理属性)
示例脚本(针对含WKT字段的JSON)
假设你的原始JSON结构如下(每条数据含WKT和其他属性):
[ { "timestamp": "2025-06-10T13:15:00.000Z", "wkt": "POINT (-123.00000 12.00000)" }, { "timestamp": "2025-06-10T13:20:00.000Z", "wkt": "POINT (-122.50000 11.80000)" } ]
对应的转换脚本:
import json from shapely import wkt from shapely.geometry import mapping def json_to_geojson(input_path, output_path): # 读取原始JSON with open(input_path, 'r', encoding='utf-8') as f: raw_data = json.load(f) geojson = { "type": "FeatureCollection", "features": [] } for item in raw_data: # 解析WKT为几何对象 geom = wkt.loads(item['wkt']) # 转换为GeoJSON格式的geometry字典 geometry = mapping(geom) # 构造Feature feature = { "type": "Feature", "geometry": geometry, "properties": { # 除WKT外的其他属性都放入properties "timestamp": item['timestamp'] # 可添加更多属性字段 } } geojson['features'].append(feature) # 写入GeoJSON文件 with open(output_path, 'w', encoding='utf-8') as f: json.dump(geojson, f, indent=2) # 调用示例 json_to_geojson('input.json', 'output.geojson')
示例脚本(针对含lon/lat字段的JSON)
若原始JSON用单独字段存储经纬度:
[ { "timestamp": "2025-06-10T13:15:00.000Z", "lon": -123.0, "lat": 12.0 } ]
转换脚本:
import json def json_to_geojson(input_path, output_path): with open(input_path, 'r', encoding='utf-8') as f: raw_data = json.load(f) geojson = { "type": "FeatureCollection", "features": [] } for item in raw_data: feature = { "type": "Feature", "geometry": { "type": "Point", "coordinates": [item['lon'], item['lat']] # GeoJSON坐标顺序是[经度, 纬度] }, "properties": { "timestamp": item['timestamp'] } } geojson['features'].append(feature) with open(output_path, 'w', encoding='utf-8') as f: json.dump(geojson, f, indent=2) json_to_geojson('input.json', 'output.geojson')
内容的提问来源于stack exchange,提问作者Ashford
相关产品推荐
相关产品推荐

