python - 在 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())
解决方案
将您的 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']
推荐阅读
- codenameone - 代号一组件的完整列表
- android - 我无法加入 volley 1.1.1 在叙利亚,这是被禁止的,但我使用代理。有没有办法交流?
- php - 如何在 Laravel 5.5 中将数据插入表格并获取电子邮件通知?
- openstreetmap - 源和目的地之间的 OpenStreetMap 距离
- python - weasyprint 与 django 将数字呈现为图像
- python - 如何使用 Monte-Carlo 方法(在 python 中)估计振荡曲线的整数
- .net-core - 使用简单过滤器返回列表的实体框架查询
- php - 从子数组(PHP)中将数据推送到父数组
- sql - 操作数数据类型 varchar(max) 对除法运算符无效
- r - 在 R 中保存摘要对象列表