我有下面的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