我正在尝试从 Python 中的 json 文件中获取所有密钥。 如何获得嵌套的二级(x,y) 和三级键(a,b)。 例如,键:results,x,y,a,b
代码:
#open data
import json
with open('list.json') as f:
my_dict = json.load(f)
#1
#find keys
for key in my_dict.keys():
print("Keys : {}".format(key))
杰森:
{
"results":[
{
"x":5
},
{
"x":5,
"y":[
1,
2,
3
]
},
{
"x":5,
"y":{
"a":2,
"b":67
}
}
]
}
输出:
Keys : results
答案 0 :(得分:0)
使用递归函数返回所有嵌套的键。这是参考 stackoverflow 页面。
import json
def recursive_items(dictionary):
for key, value in dictionary.items():
if type(value) is list:
for i in value:
if type(i) is dict:
yield from recursive_items(i)
else:
yield key
with open('list.json') as f:
my_dict = json.load(f)
#find keys
for key in recursive_items(my_dict):
print("Keys : {}".format(key))
答案 1 :(得分:0)
您需要获取作为 JSON 值一部分的键。
因此您需要迭代 my_dict
的值而不是键。