如何在Python中将Dict嵌套在Dict数组中?

问题描述 投票:0回答:1

我有一个主题列表,我可以毫无问题地遍历主要主题部分。 但是,当我尝试获取操作时,我不断收到错误。 以下是一个主题的语法:

Topics
[
    {
        "Topic Id": null,
        "Topic Name": null,
        "Actions": {
            "actions": [
                {
                    "action_id": "1",
                    "action_title": "Review Video",
                    "action_summary": "Watch the video.",
                    "assigned_to": "[email protected]",
                    "due_date": "2024-05-24",
                    "action_attachments": [],
                    "action_owner": "Rumble",
                    "action_status": "Open"
                },
                {
                    "action_id": "2",
                    "action_title": "Review Barker Dam Annual Spill",
                    "action_summary": "Read the email about Barker Dam\u2019s Annual Spill Expected in Coming Days.",
                    "assigned_to": "[email protected]",
                    "due_date": "2024-05-24",
                    "action_attachments": [],
                    "action_owner": "Your neighbors",
                    "action_status": "Open"
                },
            ]
        }
    }
]

我已经尝试了我能想到的一切,现在是:

for this_action in this_topic["Actions"]["actions"]:

我已经尝试过

["Action"].get("actions")
["Action"][0]

我不断收到错误:

TypeError: list indices must be integers or slices, not str

有人可以帮我找出我做错了什么吗?

python json
1个回答
0
投票

您的代码应该可以工作,但如果您正在解析 JSON,那么其中一个

Actions
可能包含
array
而不是对象。

确保根据架构验证您的输入。

您可以添加一个简单的检查来找出导致错误的原因:

for topic in json.loads(topics):
  if isinstance(topic["Actions"], dict):
    for action in topic["Actions"]["actions"]:
      print(action["action_title"])
  else:
    print(f"ERROR: Topic 'Actions' should be a dictionary: {topic['Topic Name']}")

我可以使用以下输入重现确切的错误(第二个主题包含):

import json

topics = """[
  {
    "Topic Id": null,
    "Topic Name": "First topic",
    "Actions": {
      "actions": [
        {
          "action_id": "1",
          "action_title": "Review Video",
          "action_summary": "Watch the video.",
          "assigned_to": "[email protected]",
          "due_date": "2024-05-24",
          "action_attachments": [],
          "action_owner": "Rumble",
          "action_status": "Open"
        },
        {
          "action_id": "2",
          "action_title": "Review Barker Dam Annual Spill",
          "action_summary": "Read the email about Barker Dam\u2019s Annual Spill Expected in Coming Days.",
          "assigned_to": "[email protected]",
          "due_date": "2024-05-24",
          "action_attachments": [],
          "action_owner": "Your neighbors",
          "action_status": "Open"
        }
      ]
    }
  },
  {
    "Topic Id": null,
    "Topic Name": "Second topic",
    "Actions": [
      {
        "action_id": "1",
        "action_title": "Review Video",
        "action_summary": "Watch the video.",
        "assigned_to": "[email protected]",
        "due_date": "2024-05-24",
        "action_attachments": [],
        "action_owner": "Rumble",
        "action_status": "Open"
      },
      {
        "action_id": "2",
        "action_title": "Review Barker Dam Annual Spill",
        "action_summary": "Read the email about Barker Dam\u2019s Annual Spill Expected in Coming Days.",
        "assigned_to": "[email protected]",
        "due_date": "2024-05-24",
        "action_attachments": [],
        "action_owner": "Your neighbors",
        "action_status": "Open"
      }
    ]
  }
]
"""

for topic in json.loads(topics):
  # Check the type of `topic["Actions"]` here
  for action in topic["Actions"]["actions"]:
      print(action["action_title"])
© www.soinside.com 2019 - 2024. All rights reserved.