我有一个 API,它的响应是这样的 json:
{
"a":1,
"b":2,
"c":[
{
"d":4,
"e":5,
"f":{
"g":6
}
}
]
}
我怎样才能写一个python程序来给我 key
['d','e','g']
.我试过的是:jsonData = request.json() #request is having all the response which i got from api
c = jsonData['c']
for i in c.keys():
key = key + str(i)
print(key)
最佳答案
仅返回不包含字典作为其值的键的函数。
jsonData = {
"a": 1,
"b": 2,
"c": [{
"d": 4,
"e": 5,
"f": {
"g": 6
}
}]
}
def get_simple_keys(data):
result = []
for key in data.keys():
if type(data[key]) != dict:
result.append(key)
else:
result += get_simple_keys(data[key])
return result
print get_simple_keys(jsonData['c'][0])
避免使用递归更改行
result += get_simple_keys(data[key])
至 result += data[key].keys()
关于json - 在python中从json获取 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34327719/