Python ---- TypeError:字符串索引必须是整数

时间:2015-11-16 16:53:22

标签: python integer typeerror

我有以下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:AG@AG.com"
                                         },
                        "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

知道&#34;标识符&#34; field是一个字符串,我在URL中传递以下内容:

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新手!

2 个答案:

答案 0 :(得分:2)

问题是您正在尝试迭代字典而不是其中的数据源列表。因此,您将遍历字典的键,即字符串。另外,正如上面提到的,如果对列表和迭代器变量使用相同的名称,则会遇到问题。

这对我有用:

[ds for ds in dataset['dataset'] if ds['identifier'] == dataset_identifier]

答案 1 :(得分:1)

您现在遇到的问题是,在列表推导的迭代过程中,第一次迭代会将名称dataset更改为dictjson.loads - 更改为密钥dictdict s迭代他们的密钥)。因此,当您尝试使用datasetdataset['identifier']中查找值时,dataset不再是dict,而是您的str密钥目前正在迭代。

停止重复使用相同的名称来表示不同的事情。

根据您发布的JSON,您可能想要的是:

with open('C:/test.json', encoding="latin-1") as f:
    alldata = json.loads(f.read())

@app.route('/api/PDL/<string:dataset_identifier>', methods=['GET'])
def get_task(dataset_identifier):
    # Gets the list of data objects from top level object
    # Could be inlined into list comprehension, replacing dataset with alldata['dataset']
    dataset = alldata['dataset']
    # data is a single object in that list, which should have an identifier key
    # data_for_id is the list of objects passing the filter
    data_for_id = [data for data in dataset if data['identifier'] == dataset_identifier]
    if len(task) == 0:
        abort(404)
    return jsonify({'dataset': data_for_id})