1

Is there a way to traverse a JSON when the index are in a list in Python.

JSON:

{
 "id" : "abc",
"Obj1":
    {
        "Obj1":{
             "Name" : "123456789"
             }
    }
}

Conventionally we can access JSON index as:

data['Obj1']['Obj1']['Name'] >>Output is 123456789

But how to traverse this and change the value in same 'data' json object if the index are in a list like:

['Obj1','Obj1','Name']

Need a way to traverse to the location by using list in place of hard code index.

I need to replace the value also with 'XYZ' so final json should be "{ "id" : "abc", "Obj1": { "Obj1":{ "Name" : "XYZ" } } }"

0

1 Answer 1

1

You can use functools.reduce with dict.get:

from functools import reduce
path = ['Obj1','Obj1','Name']
print(reduce(lambda a, b: a[b], path, data))

This returns: 123456789

If you need to assign a new value 'XYZ' to the dict at the given path, you would then need to do it at a level above the leaf:

reduce(lambda a, b: a[b], path[:-1], data)[path[-1]] = 'XYZ'
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, but if i need to change the value in the original json object then?
Not sure what you mean.. won't evaluating reduce(dict.get, path, data) again do?
I mean from reduce I will get the value but I need to replace the value also with 'XYZ' so final json should be "{ "id" : "abc", "Obj1": { "Obj1":{ "Name" : "XYZ" } } }"
Hi Just noticed if the element is an List this fails.
I've updated my answer with a more general solution then.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.