我已經開發出具有請求模塊POST請求和我檢索JSON,這是代碼Python的讀JSON響應和追加
headers_ = {'Authorization': acc_token}
params_ = (('start_time', '2016-08-01T00:00:00+00:00'),('limit', '2'))
r = requests.get('https://server.com/API/v1', headers=headers_, params=params_)
data_ = r.json()
json_result = (json.dumps(data_, indent=4, sort_keys=False))
,這是JSON結果
{
"loc":[
{
"origin":{
"lat":39.72417,
"lng":-104.99984,
"eta_seconds":null,
"address":""
},
"destination":{
"lat":39.77446,
"lng":-104.9379,
"eta_seconds":null,
"address":null
}
},
{
"origin":{
"lat":39.77481,
"lng":-104.93618,
"eta_seconds":null,
"address":"10 Albion Street"
},
"destination":{
"lat":39.6984,
"lng":-104.9652,
"eta_seconds":null,
"address":null
}
}
] } 現在我試圖在數組中追加每個json條目數組的lat和lng值,並且我嘗試使用此代碼
for i in json_result:
print(i['loc']['origin']['lat'])
dict.append(i['loc']['origin']['lat'])
,但我有這個錯誤 類型錯誤:字符串索引必須是整數,而不是str的
我怎樣才能檢索到緯度值和LNG爲數組中的每個元素和追加到字典?
感謝
它不應該是'我[ 'LOC'] [1] [ '原點'] [ 'LAT']'。由於'loc'包含一個字典列表。 – kstullich
我收到相同的錯誤 – APPGIS
當我把你的JSON結果放到一個變量中並執行print(data [「loc」] [1] [「origin」] [「lat」])時,我得到所需的輸出。 – kstullich