如何将gdb数据转换为Geojson,其实可以利用QGIS,理论上来讲,凡是QGIS支持导入导出的数据,都可以进行转换。原因是QGIS可以先将加载他所支持的格式,加载完之后就变成了QGIS自己的格式,然后就能导出,导出为它可以支持导出的格式,相当于有一个中间格式。
当然,本文的重点是把gdb转换为一个geojson,利用python代码很方便,我这里使用的QGIS3.18,在QGIS的python控制台里进行运行
一个geojson可以有多种几何类型(点、线、面)的数据
1
首先要在QGIS里加载GDB数据
2
然后把下面的代码粘进去,设置好输出路径即可,
python
# -*- coding: utf-8 -*-
"""
修复 QByteArray 导出错误的 GeoJSON 导出脚本
"""
from qgis.core import *
import json
import base64 # 关键:添加 base64 编码支持
def export_layers_to_geojson(output_path):
# 获取项目所有矢量图层
layers = [layer for layer in QgsProject.instance().mapLayers().values()
if isinstance(layer, QgsVectorLayer)]
# 创建 GeoJSON 结构
geojson = {
"type": "FeatureCollection",
"features": []
}
# 自定义序列化处理器
def process_value(value):
"""处理 QByteArray 类型数据"""
if isinstance(value, QByteArray):
# 转换为 Base64 字符串(JSON 兼容格式)
return base64.b64encode(value.data()).decode('utf-8')
return value
# 遍历所有图层要素
for layer in layers:
for feature in layer.getFeatures():
# 处理属性表(修复 QByteArray)
properties = {}
for field in feature.fields():
value = feature[field.name()]
properties[field.name()] = process_value(value)
# 获取几何对象(WKT格式)
geom = feature.geometry()
if not geom.isNull():
# 转换为 GeoJSON 兼容几何
geom_json = json.loads(geom.asJson())
else:
geom_json = None
# 构建 GeoJSON 要素
geojson["features"].append({
"type": "Feature",
"geometry": geom_json,
"properties": properties
})
# 写入文件(RFC7946 标准格式)
with open(output_path, 'w', encoding='utf-8') as f:
json.dump(geojson, f,
ensure_ascii=False,
indent=2,
default=str) # 关键:处理非常规类型
print(f"✅ 成功导出至: {output_path}")
# 使用示例
export_layers_to_geojson("C:/D/project/zp/八条河/output/林地/林草地.geojson")