data_dict = {
"foo1": "bar1",
"foo2": [{"bar2": "koko"}, {"bar3": "koko2"} ],
"foo3": {
"foo4": "bar4",
"foo5": {
"foo6": "bar6",
"foo7": "bar7",
},
}
}
I need a Python function that get JSON and path of keys string like "foo2[0].bar2"
and return from dict the data_dict[foo2][0][bar2]
no matter if its an inner list/dict and no matter how many keys to get. there is some external package in Python for this functionality?
You can look into jmespath -
pip install jmespath
import jmespath
data_dict = {
"foo1": "bar1",
"foo2": [{"bar2": "koko"}, {"bar3": "koko2"} ],
"foo3": {
"foo4": "bar4",
"foo5": {
"foo6": "bar6",
"foo7": "bar7",
},
}
}
print(jmespath.search('foo2[0].bar2' , data_dict))
>> koko
Parse the path into keys and indices.
key = "foo2[0].bar2"
keys = tuple(
int(x) if x.isdigit() else x
for x in key.replace("[", ".").replace("]", "").split(".")
)
curr = data_dict
for k in keys:
curr = curr[k]
print(curr)
# koko
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.