简体   繁体   English

用于获取 JSON 上所有内部值的 Python 函数

[英]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",
     },
  }
}

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.我需要一个 Python 函数来获取 JSON 和键字符串的路径,例如"foo2[0].bar2"并从 dict 返回data_dict[foo2][0][bar2]无论它是否是内部列表/dict,无论如何许多钥匙得到。 there is some external package in Python for this functionality? Python 中有一些用于此功能的外部包吗?

You can look into jmespath -您可以查看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

jmespath tutorials jmespath 教程

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM