类型错误:列表索引必须是整数或切片,而不是字符串

0 投票
1 回答
41 浏览
提问于 2025-04-14 16:07

我正在尝试遍历不同的GeoJSON文件,但遇到了一个错误。

     20     for feature in features:
     21         # Extract properties and geometry
---> 22         properties = feature['properties']
     23         geometry = feature['geometry']
     24 

错误类型:TypeError:列表索引必须是整数或切片,而不是字符串。

我的GeoJSON文件结构是这样的:

{"type":"FeatureCollection","name":"10","crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:OGC:1.3:CRS84"}},"features":[[{"type":"Feature","properties":{"Id":"75"},"geometry":{"type":"MultiPolygon","coordinates":[[[[["71.000348","31.199419"],["71.00038","31.198841"],["71.000294","31.198832"],["71.000294","31.197318"],["71.0006","31.197379"],["71.000712","31.197094"],["71.000718","31.196727"],["71.001088","31.19675"],["71.001329","31.196746"],["71.001426","31.196759"],["71.001442","31.197227"],["71.001463","31.197792"],["71.001409","31.198853"],["71.001356","31.199478"],["71.000348","31.199419"]]]]]}},{"type":"Feature","properties":{"Id":"77"},"geometry":{"type":"MultiPolygon","coordinates":[[[[["72.469083","31.00806"],["72.469083","31.00806"],["72.470054","31.009012"],["72.470054","31.009012"],["72.471138","31.008148"],["72.471138","31.008148"],["72.47021","31.007159"],["72.47021","31.007159"],["72.469083","31.00806"]]]]]}}]]}

import json
import glob
import geopandas as gpd
import geemap

# Specify the folder path containing GeoJSON files
folder_path = 'D:/Test'

# Get a list of all GeoJSON files in the folder
geojson_files = glob.glob(folder_path + '/*.geojson')

# Iterate over each GeoJSON file
for geojson_file in geojson_files:
    with open(geojson_file, 'r') as f:
        data = json.load(f)
    
    # Access the features in the GeoJSON file
    features = data['features']

    for feature in features:
        # Extract properties and geometry
        properties = feature['properties']
        geometry = feature['geometry']

        # Convert to GeoDataFrame
        nReserve_feature = gpd.GeoDataFrame.from_features([{
            'geometry': geometry,
            'properties': properties
        }])

        # Load the GeoJSON string into Earth Engine
        nReserve_geojson = geemap.gdf_to_ee(nReserve_feature, geodesic=False)

我正在尝试使用唯一的ID来遍历不同GeoJSON文件中的特征。

1 个回答

1

features = data['features'] 改成 features = data['features'][0],这样可以去掉外面的列表,因为 features 的格式是 [[....]]。

撰写回答