首页 > 解决方案 > 在 Python 中检索 JSON 的所有键

问题描述

我知道这类问题已经得到解答,但提供的解决方案对我根本不起作用。我想在每个级别检索 JSON 文件中的所有键,而不仅仅是在第一级。

假设我想从以下 JSON 文件中获取所有密钥

{
    "quiz": {
        "sport": {
            "q1": {
                "question": "Which one is correct team name in NBA?",
                "options": [
                    "New York Bulls",
                    "Los Angeles Kings",
                    "Golden State Warriros",
                    "Huston Rocket"
                ],
                "answer": "Huston Rocket"
            }
        },
        "maths": {
            "q1": {
                "question": "5 + 7 = ?",
                "options": [
                    "10",
                    "11",
                    "12",
                    "13"
                ],
                "answer": "12"
            },
            "q2": {
                "question": "12 - 8 = ?",
                "options": [
                    "1",
                    "2",
                    "3",
                    "4"
                ],
                "answer": "4"
            }
        }
    }
}

我到目前为止的进展

for k,v in json_object.items():
    print(v.keys())

标签: pythonjsonpython-3.x

解决方案


将您的 json 内容作为 dict 存储在变量中,即data

data = {
    "quiz": {
        "sport": {
            "q1": {
                "question": "Which one is correct team name in NBA?",
                "options": [
                    "New York Bulls",
                    "Los Angeles Kings",
                    "Golden State Warriros",
                    "Huston Rocket"
                ],
                "answer": "Huston Rocket"
            }
        },
        "maths": {
            "q1": {
                "question": "5 + 7 = ?",
                "options": [
                    "10",
                    "11",
                    "12",
                    "13"
                ],
                "answer": "12"
            },
            "q2": {
                "question": "12 - 8 = ?",
                "options": [
                    "1",
                    "2",
                    "3",
                    "4"
                ],
                "answer": "4"
            }
        }
    }
}

使用以下递归方法获取所有密钥...

def get_keys(d, indent=0, parent=""):
    print("{}{}{}{}".format(" "*indent*4, parent, " => " if parent else "", list(d.keys())))

    for key in d:
        if isinstance(d[key], dict):
            get_keys(d[key], indent=indent+1, parent=key)

当您调用如下方法时:

get_keys(data)                                                                                                                                                                                        

你会得到输出为:

['quiz']
    quiz => ['sport', 'maths']
        sport => ['q1']
            q1 => ['question', 'options', 'answer']
        maths => ['q1', 'q2']
            q1 => ['question', 'options', 'answer']
            q2 => ['question', 'options', 'answer']

推荐阅读