Home > Net >  Python function to get all inner values on JSON
Python function to get all inner values on JSON

Time:10-27

contextlib import suppress

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 something in Python already do this

CodePudding user response:

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

jmespath tutorials

CodePudding user response:

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
  • Related