我想撰寫一個函式來訪問字典鍵并在鍵存在時重命名它。例如:
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"] 可以是鍵的任意組合,但如何將它們作為引數傳遞?
uj5u.com熱心網友回復:
我會傳入一個代表目標鍵“路徑”的串列。例如:
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')
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/403348.html
標籤:
上一篇:試圖將串列陣列轉換為物件?
下一篇:如何保存大型Json資料?
