开发者社区> 问答> 正文

如何从嵌套词典中获取单个词典?

具有以下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"
    }
  }
}

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

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)

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

问题来源:stackoverflow

展开
收起
is大龙 2020-03-23 17:33:36 455 0
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(\*ist_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'}
    

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

    回答来源:stackoverflow

    2020-03-23 17:33:44
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载