Home > Software engineering >  Python how to access specific json dictionary value by chaining the 'key'
Python how to access specific json dictionary value by chaining the 'key'

Time:12-20

If I have the following Json:

{
"a": {
       "b" : {
               "c" : "value"
             }
      }
}

This is loaded into my object (obj) via json.load()

Then I have another variable which is

path = "a.b.c"

To access the value of 'c' in the json, I would typically do:

obj["a"]["b"]["c"]

However I would like to leverage the 'path' variable, and do something like this:

obj[path]

Is this possible? How can this be achieved

CodePudding user response:

It's possible to do so using a combination of operator.getitem and functools.reduce:

>>> from functools import reduce
>>> from operator import getitem
>>> dct = {'a': {'b': {'c': 'value'}}}
>>> reduce(getitem, "a.b.c".split("."), dct)
'value'

CodePudding user response:

You can split the path on dot and use reduce to get the nested value.

from functools import reduce
d = {'a':{'b':{'c':'value'}}}
path = "a.b.c"
val = reduce(lambda o, k: o[k], path.split("."), d)
print(val)

Demo

CodePudding user response:

You could write a function that takes both the JSON data and the path as arguments. It can iterate through each key in the path (separated by .) and traverse through the JSON that way.

def json_from_path(data: dict, path: str):
    for key in path.split('.'):
        data = data[key]
    return data
  • Related