在Python中检索JSON的所有键
我知道这类问题已经得到了回答,但提供的解决方案根本不适合我。我希望在每个级别检索JSON文件中的所有键,而不仅仅是在第一个级别 假设我想从下面的JSON文件中获取所有密钥在Python中检索JSON的所有键,python,json,python-3.x,Python,Json,Python 3.x,我知道这类问题已经得到了回答,但提供的解决方案根本不适合我。我希望在每个级别检索JSON文件中的所有键,而不仅仅是在第一个级别 假设我想从下面的JSON文件中获取所有密钥 { "quiz": { "sport": { "q1": { "question": "Which one is correct team name in NBA?", "options": [
{
"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())
将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']
到目前为止你尝试了什么?@Gahan很抱歉,我没有添加我的进度,所以我只是问有人会如何从头开始处理问题。谢谢你的反馈。