How To Dynamically Get The Json Path And Modify The Json Field Value With The Path
I have a lot of json files, their structure is different. I need to change the value of a field in json every time, the values of other fields remain unchanged. Now I have been abl
Solution 1:
Here's the basic idea of how to do it with the path
that is a sequence of keys:
from functools import reduce
# From https://stackoverflow.com/a/28225747/355230defrecursive_get(d, *keys):
return reduce(lambda c, k: c.get(k, {}), keys, d)
t_json = loadJson()
path = ['glossary', 'GlossDiv', 'title']
sub_dict = recursive_get(t_json, *path[:-1])
sub_dict['title'] = 'M'print(t_json)
Solution 2:
How to get
t_json[path[0]][path[1]][path[2]]
?
Simple: we just need to iterate over path
, applying one indexing operation at a time. This requires that we remember our progress after each step, and the simplest way is to just reuse a variable that traces its way through the path. Thus, for example:
element = t_json
for path_item inpath:
element = element[path_item]
Post a Comment for "How To Dynamically Get The Json Path And Modify The Json Field Value With The Path"