python替换key值_python替换json指定key的值

本文介绍如何使用Python递归遍历JSON对象,通过findKeyPath函数定位到特定键路径,并利用replace函数实现替换操作。实例演示了对列表和字典结构的处理,适合对数据结构操作感兴趣的开发者。
摘要由CSDN通过智能技术生成

'''

替换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"])

'''

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值