My json data would look like this
{
"a":1,
"b":[
{
"c":2,
"d":{
"e":3
},
"f":{
"g":4
},
"h":[
{
"i":5
},
{
"j":6
}
]
}
]
}
Is there a way I can extract all the keys from the response. What I would want is like: [a,b,c,d,e,f,g,h,i,j]. Can this be done?
CodePudding user response:
You can use recursive function and iterate over all items in dict.
def get_all_key(dct, lst):
for k,v in dct.items():
lst.append(k)
if isinstance(v, list):
for d in v:
get_all_key(d, lst)
elif isinstance(v, dict):
get_all_key(v, lst)
res = []
get_all_key(dct, res)
print(res)
Output:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
CodePudding user response:
You can solve it, using generators, for example:
def get_keys(d):
if isinstance(d, dict):
for k, v in d.items():
yield k
yield from list(get_keys(v))
elif isinstance(d, list):
for o in d:
yield from list(get_keys(o))
print(list(get_keys(adict)))
Output:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
CodePudding user response:
Recursion (Depth-First Search) would be a go to for this:
def get_keys(data):
keys = []
if isinstance(data, dict):
for key, value in data.items():
keys.append(key)
keys = get_keys(value)
elif isinstance(data, list):
for value in data:
keys = get_keys(value)
return keys
print(get_keys(data=response))
CodePudding user response:
Adding to the above correct answers, this is also a method.
I mean there are a lot of ways in which we can do this, but they say smallest amount of work is the best work.
If all you data only string as keys and no key in the string, we can do this:
import json
import re
json_text = json.dumps(a)
print([_.replace('"', "") for _ in re.findall(r"\"\w\"", json_text)])
Convert dictionary to json, find all the matching "a"
where a
is the character, then remove the "
from all matches and voila..
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']