[英]Python function to get all inner values on JSON
data_dict = {
"foo1": "bar1",
"foo2": [{"bar2": "koko"}, {"bar3": "koko2"} ],
"foo3": {
"foo4": "bar4",
"foo5": {
"foo6": "bar6",
"foo7": "bar7",
},
}
}
我需要一個 Python 函數來獲取 JSON 和鍵字符串的路徑,例如"foo2[0].bar2"
並從 dict 返回data_dict[foo2][0][bar2]
無論它是否是內部列表/dict,無論如何許多鑰匙得到。 Python 中有一些用於此功能的外部包嗎?
您可以查看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
將路徑解析為鍵和索引。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.