如何解决TypeError:列表索引必须是整数或切片,而不是python中的str



情况

我正在尝试访问json字符串内的值,但收到错误:

TypeError:列表索引必须是整数或切片,而不是str

JSON

j={
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
2.44775,
48.925778
]
},
"properties": {
"country_code": "fr",
"housenumber": "15",
"street": "Rue Leon Bernard",
"distance": 16.948223707815888,
"country": "France",
"county": "Seine-Saint-Denis",
"datasource": {
"sourcename": "openaddresses",
"attribution": "© OpenAddresses contributors",
"license": "BSD-3-Clause License"
},
"postcode": "93700",
"state": "Ile-of-France",
"district": "Drancy",
"city": "Drancy",
"lon": 2.44775,
"lat": 48.925778,
"result_type": "building",
"formatted": "15 Rue Leon Bernard, 93700 Drancy, France",
"address_line1": "15 Rue Leon Bernard",
"address_line2": "93700 Drancy, France",
}
}
]
}

目标

我需要获得country_code和国家的值,我已经尝试过

j['features']['properties'][0]` 

:

如何在python中获得这两个字段的值?

在json中,您提供的'features'值是一个列表,因此您需要相应地索引它。

j['features'][0]['properties']

从这里你应该能够简单地继续访问'properties'的所有值

相关内容

最新更新