【问题标题】:How to get individual dict from a nested dict?如何从嵌套字典中获取单个字典?
【发布时间】:2020-03-16 11:24:13
【问题描述】:

有以下 json 文件

{
  "front_page": {
    "institue": {
      "inst_name": "University Name",
      "size": 12,
      "type": "bold"
    },
    "doc_type": {
      "name": "(Scope Document)",
      "size": 12,
      "type": "bold"
    },
    "project_title": {
      "name": "Project Title",
      "size": 12,
      "type": "bold"
    },
    "Version": {
      "Version": "Version 1.0",
      "size": 12,
      "type": "bold"
    },
    "Degree": {
      "name": "Becholar of Science in Computer Science(2016-2020)",
      "size": 12,
      "type": "bold"
    }
  }
}

我需要将所有嵌套字典作为单独的 dict 对象。 到目前为止,我只设法获得了所有键值对

def parse_json_obj(json_obj):
    for k, v in json_obj.items():
        if isinstance(v, dict):
            print('found at ', k)
            parse_json_obj(v)
        else:
            print(v)

我想要做的是获取每个 dict 并将其内容附加到 pdf 页面。我已经想出了如何处理 pdf 的每个字典,但不知道如何提取字典。 任何帮助,将不胜感激。

【问题讨论】:

  • 很不清楚你在这里的意思。您正在递归地执行您所说的操作。你检查 v 是否是一个字典。如果是,那么 v 就是那个单独的字典。那么你想用 v 做什么呢?
  • 你能发布你的预期输出吗?

标签: json python-3.x dictionary


【解决方案1】:

假设您想要的是所有没有子字典的字典,您可以执行以下操作。

jdict = {
    "front_page": {
        "institue": {
            "inst_name": "University Name",
            "size": 12,
            "type": "bold"
        },
        "doc_type": {
            "name": "(Scope Document)",
            "size": 12,
            "type": "bold"
        },
        "project_title": {
            "name": "Project Title",
            "size": 12,
            "type": "bold"
        },
        "Version": {
            "Version": "Version 1.0",
            "size": 12,
            "type": "bold"
        },
        "Degree": {
            "name": "Becholar of Science in Computer Science(2016-2020)",
            "size": 12,
            "type": "bold"
        }
    }
}


def parse_json_obj(json_obj):
    list_of_dicts = []
    for item in json_obj.values():
        if isinstance(item, dict):
            has_sub_dict = [subdict for subdict in item.values() if isinstance(subdict, dict)]
            if has_sub_dict:
                list_of_dicts += parse_json_obj(item)
            else:
                list_of_dicts.append(item)
    return list_of_dicts

list_of_dicts = parse_json_obj(jdict)
print(*list_of_dicts, sep="\n")

输出

{'inst_name': 'University Name', 'size': 12, 'type': 'bold'}
{'name': '(Scope Document)', 'size': 12, 'type': 'bold'}
{'name': 'Project Title', 'size': 12, 'type': 'bold'}
{'Version': 'Version 1.0', 'size': 12, 'type': 'bold'}
{'name': 'Becholar of Science in Computer Science(2016-2020)', 'size': 12, 'type': 'bold'}

如果这不是您想要达到的目标,那么我建议您更新问题以使其更清楚。

【讨论】:

  • 感谢我正在寻找的东西。你拯救了这一天
猜你喜欢
  • 2021-06-02
  • 1970-01-01
  • 2019-12-04
  • 1970-01-01
  • 2021-05-10
  • 1970-01-01
  • 2021-12-24
  • 2018-01-29
  • 1970-01-01
相关资源
最近更新 更多