首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将Python字典导出到Geojson -从'coordinates‘值中移除双引号

将Python字典导出到Geojson -从'coordinates‘值中移除双引号
EN

Stack Overflow用户
提问于 2018-04-14 21:32:59
回答 2查看 986关注 0票数 1

除了coordinates键之外,Geojson format本质上几乎是常规的JSON:

代码语言:javascript
复制
{ 
    "type": "Feature",
    "geometry": 
        {
            "type": "LineString",
            "coordinates": [
                [10, 20], [30, 40]
            ]
        }
}

与常规JSON的不同之处在于,关键字coordinates的值没有双引号(在地理信息系统中我们称之为原始几何数据)。

在Python中,普通的JSON可以仅仅是普通的dict() --所以为了简单起见,这是我想用来存储和导出Geojson数据的方式:

代码语言:javascript
复制
# 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'迭代键值并将其写入文本文件等的解决方案。

EN

回答 2

Stack Overflow用户

发布于 2018-04-14 23:12:07

python字典的值(和键)不一定是字符串。实际上,您已经使用了一个列表作为关键“特性”的值。

您可以简单地在坐标字段中指定列表列表。

代码语言:javascript
复制
geojson_dict['features'][0]['geometry']['coordinates'] = [[10, 20], [30, 40]]

另外,我建议你看看GeoJSON package。这是一个处理GeoJSON对象(几何、特征、集合)的有用的库。

票数 2
EN

Stack Overflow用户

发布于 2018-04-14 22:48:08

您可以使用ast库中的literal_eval()函数从字典值中删除双引号。在提供的JSON数据中,我们可以这样做:

代码语言:javascript
复制
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]]}}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49831993

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档