0

What is the simplest way to access a field in json data if entire key-address is given in a list.

E.g., Given "data" a json object and ["context", "body", "gk"] as the list of keys, i.e.

resultant value = data["context"]["body"]["gk"]

In this, list of keys can be of any length.

Is there any simpler approach to this?

target = json.loads(data)
for elem in key_list:
    target = target[elem]
print target
padmanabh pande
  • 367
  • 2
  • 4
  • 21

1 Answers1

1

Hah, good question! You need to repeatedly apply a function (dict.get), and the tool for this is reduce. Like this:

path = ["context", "body", "gk"]
data = {"context": { "body": {"gk": 42 }}}

from functools import reduce
print(reduce(dict.get, path, data))
# output: 42

If you have a dict-like object that might or might not have overridden the get method, you can use its get method instead of dict.get, like this:

reduce(type(data).get, path, data)
alexis
  • 48,685
  • 16
  • 101
  • 161