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

如何从嵌套JSON提取名称、经纬度并转换为CSV文件?

解决GeoJSON数据提取与CSV转换问题

首先得明确你要处理的是标准GeoJSON格式数据,结构逻辑是:

  • 顶层的features是一个数组,每个元素对应一个着陆点的完整信息
  • 每个feature对象中:
    • 城市名存储在properties.name字段
    • 经纬度存储在geometry.coordinates里,格式为[经度, 纬度]

你之前用data['features.name']是错误的——既不存在这个键名,也忽略了features是数组的特性,必须遍历数组逐个提取元素内的字段。

以下是修正后的完整代码,包含数据提取与CSV文件生成:

import json
import csv

def cables():
    json_file = 'exitpoints.json'
    
    # 读取JSON文件内容
    with open(json_file) as json_data:
        data = json.load(json_data)
    
    # 定义CSV表头和数据容器
    csv_headers = ['cityname', 'longitude', 'latitude']
    csv_rows = []
    
    # 遍历所有着陆点数据,提取所需字段
    for feature in data['features']:
        city_name = feature['properties']['name']
        longitude = feature['geometry']['coordinates'][0]
        latitude = feature['geometry']['coordinates'][1]
        csv_rows.append([city_name, longitude, latitude])
    
    # 将数据写入CSV文件
    with open('landing_points.csv', 'w', newline='', encoding='utf-8') as csv_file:
        writer = csv.writer(csv_file)
        writer.writerow(csv_headers)
        writer.writerows(csv_rows)
    
    print("CSV文件已生成完成!")

# 执行函数
cables()

核心逻辑说明:

  1. 遍历data['features']数组,逐个处理每个着陆点对象
  2. 从properties字典中提取城市名称,从geometry.coordinates中拆分经纬度(GeoJSON标准为[经度, 纬度]顺序)
  3. 使用Python内置csv模块生成规范的CSV文件,避免手动拼接字符串导致的格式错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 23:34:54