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
5
Answers
You can split the path on dot and use
reduce
to get the nested value.Demo
It’s possible to do so using a combination of
operator.getitem
andfunctools.reduce
:The way this works is that reduce will initially invoke
getitem
usingdct
and the first item from the"a.b.c".split()
i.e"a"
and then the result of it is then passed togetitem
in next iteration but this time with"b"
and so on…And
getitem
in itself works like: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.It’s a third-party installation, but the
jq
package lets you traverse data structures using thejq
filter language.(Note that
.
has to precede each key, rather than simply separating the keys, in the path.)This might be a little beyond the scope of the question, but you can always subclass the
dict
type and overwrite the__getitem__
method to get the result you are looking for.This is the way that you could actually achieve the result the OP is asking for with the syntax used by the OP.
For example:
Then it’s as simple as:
OUTPUT