'''
替换json指定key的值
'''
keyPath = []
def findKeyPath(obj, newObj, keyName, currentPath):
global keyPath
for i, k in enumerate(obj):
# list
if isinstance(obj, list):
if isinstance(k, list):
if isinstance(newObj, list):
newObj.append(findKeyPath(k, list(), keyName, f"{currentPath}.{i}"))
elif isinstance(newObj, dict):
newObj[k] = findKeyPath(k, list(), keyName, f"{currentPath}.{i}")
elif isinstance(k, dict):
if isinstance(newObj, list):
newObj.append(findKeyPath(k, dict(), keyName, f"{currentPath}.{i}"))
elif isinstance(newObj, dict):
newObj[k] = findKeyPath(k, dict(), keyName, f"{currentPath}.{i}")
else:
if isinstance(newObj, list):
newObj.append(k)
elif isinstance(newObj, dict):
newObj[k] = k
# dict
elif isinstance(obj, dict):
if isinstance(obj[k], list):
if isinstance(newObj, list):
newObj.append(findKeyPath(obj[k], list(), keyName, f"{currentPath}.{k}"))
elif isinstance(newObj, dict):
newObj[k] = findKeyPath(obj[k], list(), keyName, f"{currentPath}.{k}")
elif isinstance(obj[k], dict):
if isinstance(newObj, list):
newObj.append(findKeyPath(obj[k], dict(), keyName, f"{currentPath}.{k}"))
elif isinstance(newObj, dict):
newObj[k] = findKeyPath(obj[k], dict(), keyName, f"{currentPath}.{k}")
else:
if isinstance(newObj, list):
newObj.append(obj[k])
elif isinstance(newObj, dict):
newObj[k] = obj[k]
# keyName
if k == keyName:
keyPath.append(f"{currentPath}.{k}")
#print(f"here -->{keyName} {obj[k]}")
return newObj
#findKeyPath(obj, newObj, "b", "root")
#print(f"newObj --> {newObj}")
#print(f"keyPath --> {keyPath}")
import copy
def replace(obj, replaceContent):
replacePath = []
for path in keyPath:
pathStr = ""
for s in path.split("."):
if s == "root":
pathStr += "copyObj"
elif s.isdigit():
pathStr += f"[{s}]"
else:
pathStr += f'["{s}"]'
replacePath.append(pathStr)
#print(replacePath)
# for pathStr in replacePath:
# print(eval(pathStr))
replaceObj = []
for path in replacePath:
for content in replaceContent:
copyObj = copy.deepcopy(obj)
exec(f"{path} = content")
replaceObj.append(copyObj)
print(replaceObj)
#replace(obj, ["replace1", "replace2"], keyPath)
if __name__ == "__main__":
jsonObj = {
"a": 1,
"j": "iii",
"b": {
"c": 2,
"d": 3,
"b": 4,
"a": [[0, 1, 2, {"a": 1, "b": "qq"}], "b", {"g": 7, "b": 8}]
}
}
newObj = dict()
findKeyPath(obj=jsonObj, newObj=newObj, keyName="b", currentPath="root")
replace(obj=jsonObj, replaceContent=["replace1", "replace2"])
'''
listObj = [
{
"a": 1,
"b": "iii",
"c": {"e": 3, "f": "qqq", "b": 333}
},
{
"a": 8,
"b": "mmm",
},
]
newObj = list()
findKeyPath(obj=listObj, newObj=newObj, keyName="b", currentPath="root")
replace(obj=listObj, replaceContent=["replace1", "replace2"])
'''