什么是GeoJSON?
GeoJSON是一种RFC标准化的数据格式,用于编码地理数据结构,如Point、LineString、Polygon、MultiPoint、MultiLineString和MultiPolygon。GeoJSON是基于JavaScript对象符号(JSON)的。
GeoJSON到CSV的例子
假设你有以下的GeoJSON片段。
{
"type": "FeatureCollection",
"features": [
{ "type": "Feature",
"geometry": {"type": "Point", "coordinates": [-75.343, 39.984]},
"properties": {
"name": "Location A",
"category": "Store"
}
},
{ "type": "Feature",
"geometry": {"type": "Point", "coordinates": [-80.24, 40.12]},
"properties": {
"name": "Location B",
"category": "House"
}
},
{ "type": "Feature",
"geometry": {"type": "Point", "coordinates": [ -77.2, 41.427]},
"properties": {
"name": "Location C",
"category": "Office"
}
}
]
}
你想把它转换为以下CSV格式。
latitude,longitude,altitude,geometry,name,category
39.984,-75.343,,Point,Location A,Store
40.12,-80.24,,Point,Location B,House
41.427,-77.2,,Point,Location C,Office
Python GeoJSON到CSV的转换
在Python中把GeoJSON转换为CSV的代码使用了json
和csv
包的组合。
import json
import csv
geo_filename = 'my_file.json'
csv_filename = 'my_file.csv'
def feature_to_row(feature, header):
l = []
for k in header:
l.append(feature['properties'][k])
coords = feature['geometry']['coordinates']
assert(len(coords)==2)
l.extend(coords)
return l
with open(geo_filename, 'r') as geo_file:
with open(csv_filename, 'w', newline='') as csv_file:
geojson_data = json.load(geo_file)
features = geojson_data['features']
csv_writer = csv.writer(csv_file)
is_header = True
header = []
for feature in features:
if is_header:
is_header = False
header = list(feature['properties'].keys())
header.extend(['px','py'])
csv_writer.writerow(header)
csv_writer.writerow(feature_to_row(feature, feature['properties'].keys()))
你可以复制&粘贴这段代码,并在与你的GeoJSON相同的文件夹中运行它(当然,在重命名输入和输出文件名之后。
或者你可以查看这个优秀的GitHub,以获得一个更 "可编写 "的变体,在命令行中使用。这段代码是受GitHub的启发,但大大简化了。
输入示例。
{
"type": "FeatureCollection",
"features": [
{ "type": "Feature",
"geometry": {"type": "Point", "coordinates": [-75.343, 39.984]},
"properties": {
"name": "Location A",
"category": "Store"
}
},
{ "type": "Feature",
"geometry": {"type": "Point", "coordinates": [-80.24, 40.12]},
"properties": {
"name": "Location B",
"category": "House"
}
},
{ "type": "Feature",
"geometry": {"type": "Point", "coordinates": [ -77.2, 41.427]},
"properties": {
"name": "Location C",
"category": "Office"
}
}
]
}
输出示例。
QGIS中的GeoJSON到CSV
在QGIS中,如果你有一张像这样的地图(来源)。
你可以在QGIS中直接将GEOJSON转换为CSV,点击Export
,然后Save Feature As
,在第一个下拉菜单中选择逗号分隔值[CSV]选择器。
GeoJSON到CSV在线转换器
您可以使用以下在线转换器轻松地将特定的GeoJSON片段转换为CSV。