![](/img/trans.png)
[英]How to solve "TypeError: list indices must be integers or slices, not str"
[英]how to solve TypeError: list indices must be integers or slices, not str in python
情況
我試圖訪問 json 字符串中的值但收到錯誤:
類型錯誤:列表索引必須是整數或切片,而不是 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 和country 的值我已經嘗試過
j['features']['properties'][0]`
問題:
如何在python中獲取這兩個字段的值?
在您提供的 json 中,'features' 值是一個列表,因此您需要相應地對其進行索引。
j['features'][0]['properties']
從這里您應該能夠簡單地繼續訪問“屬性”的所有值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.