You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将含GPS坐标的非标准JSON转换为GeoJSON以适配GPX转换

用正则表达式将非标准GPS JSON转换为GeoJSON点集合

可以用正则实现转换,但优先推荐使用JSON解析工具(更可靠,能处理各种合法JSON变体),以下是两种方案:

一、更稳妥的JSON解析方案(推荐)

对于大型JSON文件,用专业的JSON解析库处理是最可靠的方式,不会因为格式细微变化导致匹配失败。以Python为例:

import json

# 读取原始非标准JSON文件
with open("input.json", "r", encoding="utf-8") as f:
    raw_data = json.load(f)

# 构建标准GeoJSON FeatureCollection结构
geojson = {
    "type": "FeatureCollection",
    "features": []
}

# 遍历eventGpx数组提取坐标
for entry in raw_data.get("eventGpx", []):
    lon = entry.get("lon")
    lat = entry.get("lat")
    if lon is not None and lat is not None:
        feature = {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [float(lon), float(lat)]
            },
            "properties": {
                "s": entry.get("s")  # 可选保留原s字段,不需要可删除
            }
        }
        geojson["features"].append(feature)

# 保存为标准GeoJSON文件
with open("output.geojson", "w", encoding="utf-8") as f:
    json.dump(geojson, f, indent=2)

二、正则表达式方案(仅用于格式固定的场景)

如果因为特殊原因必须用正则,需要确保原始JSON中eventGpx数组内的lon、lat字段格式完全固定(比如字段顺序不变、无嵌套干扰、数值格式统一)。

正则匹配逻辑

  1. 先定位eventGpx数组的内容
  2. 在数组内匹配所有"lon": 数值, "lat": 数值的组合

实现代码(Python)

import re
import json

# 读取原始文件内容
with open("input.json", "r", encoding="utf-8") as f:
    content = f.read()

# 提取eventGpx数组的核心内容
gpx_match = re.search(r'"eventGpx":\s*\[(.*?)\]', content, re.DOTALL)
if not gpx_match:
    print("未找到eventGpx数组")
    exit()

# 匹配所有lon和lat坐标对
coord_pattern = re.compile(r'"lon":\s*([-+]?\d+\.?\d*),\s*"lat":\s*([-+]?\d+\.?\d*)')
coord_pairs = coord_pattern.findall(gpx_match.group(1))

# 构建GeoJSON
geojson_features = []
for lon_str, lat_str in coord_pairs:
    try:
        lon = float(lon_str)
        lat = float(lat_str)
        geojson_features.append({
            "type": "Feature",
            "geometry": {"type": "Point", "coordinates": [lon, lat]},
            "properties": {}
        })
    except ValueError:
        print(f"跳过无效坐标:lon={lon_str}, lat={lat_str}")

geojson = {
    "type": "FeatureCollection",
    "features": geojson_features
}

# 保存结果
with open("output_regex.geojson", "w", encoding="utf-8") as f:
    json.dump(geojson, f, indent=2)

正则方案的局限性

  • 如果lon和lat字段顺序颠倒、字段名有拼写差异、数值包含特殊格式(比如科学计数法),正则会匹配失败
  • 若JSON中有嵌套结构或转义引号,正则容易误判内容边界

内容的提问来源于stack exchange,提问作者hanserino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 14:55:26