我有下面的Python代碼的Python ----類型錯誤:字符串索引必須是整數
from flask import Flask, jsonify, json
app = Flask(__name__)
with open('C:/test.json', encoding="latin-1") as f:
dataset = json.loads(f.read())
@app.route('/api/PDL/<string:dataset_identifier>', methods=['GET'])
def get_task(dataset_identifier):
global dataset
dataset = [dataset for dataset in dataset if dataset['identifier'] == dataset_identifier]
if len(task) == 0:
abort(404)
return jsonify({'dataset': dataset})
if __name__ == '__main__':
app.run(debug=True)
Test.json看起來是這樣的:
{
"dataset": [{
"bureauCode": [
"016:00"
],
"description": "XYZ",
"contactPoint": {
"fn": "AG",
"hasEmail": "mailto:[email protected]"
},
"distribution": [
{
"format": "XLS",
"mediaType": "application/vnd.ms-excel",
"downloadURL": "https://www.example.com/xyz.xls"
}
],
"programCode": [
"000:000"
],
"keyword": [ "return to work",
],
"modified": "2015-10-14",
"title": "September 2015",
"publisher": {
"name": "abc"
},
"identifier": US-XYZ-ABC-36,
"rights": null,
"temporal": null,
"describedBy": null,
"accessLevel": "public",
"spatial": null,
"license": "http://creativecommons.org/publicdomain/zero/1.0/",
"references": [
"http://www.example.com/example.html"
]
}
],
"conformsTo": "https://example.com"
}
當我傳遞變量的URL像這樣:http://127.0.0.1:5000/api/PDL/1403
我得到以下錯誤:TypeError: string indices must be integers
知道「標識符」字段是一個字符串,我通過以下網址:
http://127.0.0.1:5000/api/PDL/"US-XYZ-ABC-36"
http://127.0.0.1:5000/api/PDL/US-XYZ-ABC-36
我不斷收到以下錯誤:
TypeError: string indices must be integers
什麼我錯過這裏的任何想法?我是Python新手!
不要在你的列表中理解使用相同的變量名作爲你的迭代器和列表 –
不但OP使用的名稱兩次名單補償裏面,但他也被分配了導致同名。 –
@DanielRoseman:在Py2中,這也會減慢很多東西,因爲列表組件會共享作用域(因此,所有使用'dataset'的組件都會共享全局組件,包括重新分配全局的組件),使其變得緩慢,而不僅僅是混亂。至少在Py3中,列表組件(如生成器表達式和set/dict組件)具有閉包範圍,可以保護它們免受特定的低效率影響。 – ShadowRanger