I want to write a function that accesses a dictionary key and renames it if the key exists. For example:
def json_rename(json_input, json_output, to_replace):
json_output = []
for j in json_input:
try:
j["key1"][0]["key_2"] = j["key1"][0].pop(to_replace)
json.output.append(j)
except:
json.output.append(j)
return json_output
j["key1"][0]["key_2"]
could be any combination of keys, but how do I pass those as arguments?
CodePudding user response:
I would pass in a list that represents the "path" of your target key. For example:
import contextlib
def rename_key(json_input, path, new_key):
for j in json_input:
with contextlib.suppress(KeyError):
for p in path[:-1]:
j = j[p]
j[new_key] = j[path[-1]]
del j[path[-1]]
rename_key(json_input, ['key1', 0, 'key2'], 'New Key 2')
rename_key(json_input, ['key3', 'key4', 1, 'key5'], 'New Key 5')