shp数据转json格式

import geopandas as gpd
import json
import os

# 定义输入和输出文件夹
input_folder = "shp_files"  # 存放 SHP 文件的文件夹
output_folder = "json_files"  # 存放转换后的 JSON 文件的文件夹

# 确保输出文件夹存在
if not os.path.exists(output_folder):
    os.makedirs(output_folder)

# 遍历输入文件夹中的所有 SHP 文件
for filename in os.listdir(input_folder):
    if filename.endswith(".shp"):
        # 读取 SHP 文件,尝试多种编码
        input_path = os.path.join(input_folder, filename)
        encodings = ["gbk", "gb18030", "utf-8"]  # 常见的中文编码
        data = None
        for encoding in encodings:
            try:
                data = gpd.read_file(input_path, encoding=encoding)
                print(f"成功读取文件 {input_path},编码: {encoding}")
                break
            except Exception as e:
                print(f"尝试编码 {encoding} 失败: {e}")
        if data is None:
            print(f"错误: 无法读取文件 {input_path},尝试的编码均失败。")
            continue

        # 将 GeoDataFrame 转换为字典,确保属性不丢失
        geojson_dict = {
            "type": "FeatureCollection",
            "features": [
                {
                    "type": "Feature",
                    "geometry": feature["geometry"],  # 直接使用 geometry 字典
                    "properties": {
                        key: value for key, value in feature["properties"].items()
                    }  # 确保所有属性字段保留
                }
                for feature in data.iterfeatures()
            ]
        }

        # 保存为格式化的 JSON 文件,使用 utf-8 编码
        output_path = os.path.join(output_folder, filename.replace(".shp", ".json"))
        with open(output_path, "w", encoding="utf-8") as f:
            # 使用 ensure_ascii=False 来保留非 ASCII 字符(如汉字)
            json.dump(geojson_dict, f, ensure_ascii=False, indent=4)

        print(f"转换完成: {input_path} -> {output_path}")

你可能感兴趣的:(json,python,前端)