如何从嵌套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()
核心逻辑说明:
- 遍历
data['features']数组,逐个处理每个着陆点对象 - 从
properties字典中提取城市名称,从geometry.coordinates中拆分经纬度(GeoJSON标准为[经度, 纬度]顺序) - 使用Python内置
csv模块生成规范的CSV文件,避免手动拼接字符串导致的格式错误
内容的提问来源于stack exchange,提问作者RadioActive
相关产品推荐
相关产品推荐

