如何使用python-geojson从python转储中格式化geoJSON文件?

问题描述 投票:1回答:2

我正在尝试使用python和python-geojson创建功能数组。我添加了一些功能,例如带有工作坐标的多边形。但是,当我转储时,geoJson文件中没有缩进。全部都在一行上,而mapbox不接受数据。

f

features = []
poly = Polygon([[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38, 57.322)]])


features.append(Polygon([[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38, 57.322)]]))
features.append(Feature(geometry=poly, properties={"country": "Spain"}))


feature_collection = FeatureCollection(features)

with open('myfile.geojson', 'w') as f:
   dump(feature_collection,f)
f.close()

即输出的外观。应该缩进而不是像这样聚簇。

{“ type”:“ FeatureCollection”,“ features”:[{“ type”:“ Polygon”,“ coordinates”:[[[2.38,57.322],[23.194,-20.28],[-120.43,19.15] ,[2.38,57.322]]]},{“ geometry”:{“ type”:“ Polygon”,“ coordinates”:[[[2.38,57.322],[23.194,-20.28],[-120.43,19.15], [2.38,57.322]]]},“ type”:“功能”,“ properties”:{“ country”:“西班牙”}}}}]

python geojson
2个回答
1
投票

向您的dump()调用添加'indent'参数:

with open('myfile.geojson', 'w') as f:
   dump(feature_collection, f, indent=4)

然而,奇怪的是,一段代码不会接受全部一行的JSON。它和合法的JSON一样多。那是该代码中的错误。通常仅出于人类可读性的目的使用“缩进”参数。


-1
投票

有点备份,有三种类型的GeoJSON对象:

  1. 几何
  2. 功能
  3. FeatureCollection

Feature包括Geometry,并且FeatureCollection包括一个或多个Features。您不能将Geometry直接放在FeatureCollection内,但是它必须是Feature

在您共享的示例中,您的FeatureCollection包括一个Feature和一个Geometry(在本例中为Polygon)。您需要先将Polygon转换为Feature,然后再将其添加到FeatureCollection

不确定您是否打算有两个相同的多边形,但是您的示例需要看起来像这样才能输出有效的GeoJSON:

features = []
poly1 = Polygon([[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38, 57.322)]])
poly2 = Polygon([[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38, 57.322)]])


features.append(Feature(geometry=poly1, properties={"country": "Spain"}))
features.append(Feature(geometry=poly2))


feature_collection = FeatureCollection(features)

with open('myfile.geojson', 'w') as f:
   dump(feature_collection,f)
f.close()

缩进在这里不重要。

您可以在https://tools.ietf.org/html/rfc7946上阅读更多关于GeoJSON规范的信息。

© www.soinside.com 2019 - 2024. All rights reserved.