首页 > 解决方案 > 尝试将多个项目附加到列表但得到 Python TypeError:列表索引必须是整数或切片,而不是 str

问题描述

我正在尝试遍历 customfield_10003 并为列表中的每个问题附加每个 customfield_10003 中的所有“名称”值。

这是我正在处理的 JSON:

{
        "expand": "operations,versionedRepresentations,editmeta,changelog,renderedFields",
        "fields": {
            "customfield_10003": [
                {
                    "boardId": 11,
                    "completeDate": "2021-03-24T16:16:31.040Z",
                    "endDate": "2021-03-23T14:38:00.000Z",
                    "goal": "",
                    "id": 34,
                    "name": "Promo Sim 3/23",
                    "startDate": "2021-03-10T14:38:04.147Z",
                    "state": "closed"
                },
                {
                    "boardId": 11,
                    "completeDate": "2021-04-07T14:28:50.786Z",
                    "endDate": "2021-04-06T16:33:00.000Z",
                    "goal": "User will be able to create a new promotion simulator and include simulation inputs, select a simulation type. User will be able to view simulation inputs in the \"location\" they selected. User will be able to view predictors from a model on the Predictors tab. User will be able to view simulation inputs on the Spend tab.",
                    "id": 38,
                    "name": "Promo Sim 3",
                    "startDate": "2021-03-24T16:33:56.044Z",
                    "state": "closed"
                },
                {
                    "boardId": 11,
                    "completeDate": "2021-04-21T13:04:46.984Z",
                    "endDate": "2021-04-20T22:26:00.000Z",
                    "goal": "Ability to Publish a Predictive Model, Ability to calculate promo sim metrics, View Summary Results with calced metrics (using the predictor data inserted into backend**)",
                    "id": 39,
                    "name": "Promo Sim 4",
                    "startDate": "2021-04-07T12:12:30.195Z",
                    "state": "closed"
                }
            ],
            "summary": "Simulation Type - Fix \"Remove\" button display & Update \"Volume Components\" to \"Simulation Input\""
        },
        "id": "25391",
        "key": "PA-4699",
        "self": "N/A"
    }

这是我编写的 Python 代码,目前仅获取列表中 [0] customfield_10003 的“名称”值。我不确定如何遍历列表并将每个“名称”值附加到问题列表输出中。

issue_list = []
for issue in issues:
  if issue['fields']["customfield_10003"]:
    issue_list.append([issue['key'],issue['fields']['summary'],issue["fields"] 
    ["customfield_10003"][0]["name"]])
else:
  issue_list.append([issue['key'],issue['fields']['summary']])enter code here

标签: pythonpandas

解决方案


如果您可以更好地描述您想要的输出,那么可以提供更好的答案。

这将遍历您的 json 对象并将名称拉入列表

#data = your sample json
data1 = data['fields']['customfield_10003']
names_list = [d['name'] for d in data1]

['Promo Sim 3/23', 'Promo Sim 3', 'Promo Sim 4']

推荐阅读