欢迎访问宙启技术站
智能推送

使用dumps()函数将GeoJSON特征集转换为字符串的Python代码示例

发布时间:2023-12-28 12:53:49

使用dumps()函数将GeoJSON特征集转换为字符串的Python代码示例如下:

import json

# 定义一个GeoJSON特征集
feature_collection = {
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "properties": {
                "name": "City A"
            },
            "geometry": {
                "type": "Point",
                "coordinates": [10.1, 20.2]
            }
        },
        {
            "type": "Feature",
            "properties": {
                "name": "City B"
            },
            "geometry": {
                "type": "Point",
                "coordinates": [30.3, 40.4]
            }
        }
    ]
}

# 使用dumps()函数将特征集转换为字符串
geojson_str = json.dumps(feature_collection)

# 打印转换后的字符串
print(geojson_str)

输出结果为:

{"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {"name": "City A"}, "geometry": {"type": "Point", "coordinates": [10.1, 20.2]}}, {"type": "Feature", "properties": {"name": "City B"}, "geometry": {"type": "Point", "coordinates": [30.3, 40.4]}}]}

这里的代码示例首先定义了一个GeoJSON特征集,其中包含两个特征(城市A和城市B),每个特征都有一个名称属性和一个点几何对象。然后,使用json.dumps()函数将特征集转换为字符串,并将结果存储在geojson_str变量中。最后,通过打印geojson_str变量,将转换后的字符串输出到控制台。

请注意,dumps()函数将特征集转换为标准的JSON字符串,而不是漂亮格式的字符串。如果需要以漂亮的格式输出,可以使用json.dumps()indent参数来指定缩进的空格数量,例如json.dumps(feature_collection, indent=4)