Get keys from json in python
I have an API whose response is json like this:
{
"a":1,
"b":2,
"c":[
{
"d":4,
"e":5,
"f":{
"g":6
}
}
]
}
How can I write a python program which will give me the keys ['d','e','g']
. What I tried is:
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)
Solution 1:
Function which return only keys which aren't containing dictionary as their value.
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])
To avoid using recursion change line result += get_simple_keys(data[key])
to result += data[key].keys()