Get keys from json in python
16,266
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()
Author by
Sagar
Updated on June 14, 2022Comments
-
Sagar about 2 years
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)
-
Sagar over 8 yearsThanks andriy.. It gave me
['e', 'd', 'f']
. i want 'g' rather than 'f'. I think i need one more loop inside it. -
Andriy Ivaneyko over 8 yearsyes but it wouldn't be best way ... need solution without recursion ?
-
Sagar over 8 yearsyes please that would be very helpful. Thanks again @Andriy for your effort.
-
Sagar over 8 yearswhy this is fetching in the order
['e','d','g']
rather than['d','e','g']
.. its ok but just out of curiosity. -
Andriy Ivaneyko over 8 yearsPython dictionaries are actually are hash tables. Among other things, that means the order of the keys isn't guaranteed or even specified. If you need to get them sorted use
sorted(data.keys())
before iterating them.