除了coordinates
键之外,Geojson format本质上几乎是常规的JSON:
{
"type": "Feature",
"geometry":
{
"type": "LineString",
"coordinates": [
[10, 20], [30, 40]
]
}
}
与常规JSON的不同之处在于,关键字coordinates
的值没有双引号(在地理信息系统中我们称之为原始几何数据)。
在Python中,普通的JSON可以仅仅是普通的dict()
--所以为了简单起见,这是我想用来存储和导出Geojson数据的方式:
# example fr single feature Geojson file
geojson_dict = dict()
geojson_dict['type'] = 'FeatureCollection'
geojson_dict['features'] = []
geojson_dict['features'].append(dict())
geojson_dict['features'][0]['type'] = 'Feature'
geojson_dict['features'][0]['geometry'] = dict()
geojson_dict['features'][0]['geometry']['type'] = 'LineString'
geojson_dict['features'][0]['geometry']['coordinates'] = '['+coordinates_as_string+']'
geojson_dict['features'][0]['properties'] = dict()
geojson_dict['features'][0]['properties']['id'] = 123
with open('filename.geojson', 'w') as outfile:
json.dump(geojson_dict, outfile, indent=4)
我的问题:
有没有办法继续使用Pythonic字典(或类似的容器),并去掉特定值的双引号?因为Pythonic字典默认将任何键和值用双引号括起来(就像常规JSON一样)。
备注:
我并不是在寻找使用if key == 'coordinates'
迭代键值并将其写入文本文件等的解决方案。
发布于 2018-04-14 23:12:07
python字典的值(和键)不一定是字符串。实际上,您已经使用了一个列表作为关键“特性”的值。
您可以简单地在坐标字段中指定列表列表。
geojson_dict['features'][0]['geometry']['coordinates'] = [[10, 20], [30, 40]]
另外,我建议你看看GeoJSON package。这是一个处理GeoJSON对象(几何、特征、集合)的有用的库。
发布于 2018-04-14 22:48:08
您可以使用ast
库中的literal_eval()
函数从字典值中删除双引号。在提供的JSON数据中,我们可以这样做:
import ast
geo = {
"type": "Feature",
"geometry":
{
"type": "LineString",
"coordinates": "[[10, 20], [30, 40]]"
}
}
v = geo['geometry']["coordinates"]
geo['geometry']["coordinates"] = ast.literal_eval(v)
print(geo)
Output: {'type': 'Feature', 'geometry': {'type': 'LineString', 'coordinates': [[10, 20], [30, 40]]}}
https://stackoverflow.com/questions/49831993
复制相似问题