python替换json指定key的值


'''
替换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"])
    '''
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: \u6211\u53ef\u4ee5\u56de\u7b54\u4f60\u7684\u95ee\u9898\u3002\u4e0b\u9762\u662f\u4e00\u4e2a Python \u4ee3\u7801\u7684\u793a\u4f8b\uff0c\u53ef\u4ee5\u5bf9\u67d0\u4e2a JSON \u6587\u4ef6\u4e2d\u7684\u5b57\u6bb5\u5185\u5bb9\u8fdb\u884c\u66ff\u6362\u3002 ``` import json # Sample JSON data json_data = '{"name": "Alice", "age": 30, "city": "New York"}' # Convert JSON data to Python dictionary data_dict = json.loads(json_data) # Replace the value of a specific key data_dict["age"] = 31 # Convert Python dictionary back to JSON new_json_data = json.dumps(data_dict) print(new_json_data) ``` \u8fd9\u4e2a\u793a\u4f8b\u4f7f\u7528\u4e86 Python \u7684 `json` \u6a21\u5757\uff0c\u4e3a\u4ece JSON \u6587\u4ef6\u4e2d\u5bfc\u5165\u6570\u636e\uff0c\u5c06\u5176\u8f6c\u6362\u6210 Python \u5bf9\u8c61\uff0c\u518d\u5bf9\u5bf9\u8c61\u7684\u5b57\u6bb5\u8fdb\u884c\u66ff\u6362\uff0c\u6700\u540e\u518d\u5c06\u5bf9\u8c61\u8f6c\u6362\u56de JSON \u683c\u5f0f\u7684\u6570\u636e\u3002 \u8bf7\u6ce8\u610f\uff0c\u5982\u679c\u6709\u5176\u4ed6\u95ee\u9898\uff0c\u8bf7\u4e0d\u8981\u5931\u8d25\u800c\u8fd4\u56de\u6765\uff0c\u6211\u4eec6\u4e2a\u4eba\u90fd\u4e3a\u4f60\u63d0\u4f9b\u6700\u597d\u7684\u5e94\u7b54\u3002 ### 回答2: 要替换JSON中的某个字段内容,可以使用Pythonjson库来实现。以下是一种实现方法: ```python import json def replace_json_field(json_data, field_name, new_value): # 解析JSON数据 data = json.loads(json_data) # 替换字段内容 data[field_name] = new_value # 将数据转换回JSON格式 new_json = json.dumps(data) return new_json ``` 这个函数接受三个参数:`json_data`是json数据的字符串表示,`field_name`是要替换的字段名,`new_value`是新的字段。 通过使用`json.loads()`函数,我们将json数据转换为Python的字典对象。然后,我们可以直接修改字典对象中的字段内容,将`new_value`赋给`data[field_name]`。最后,通过使用`json.dumps()`函数,我们将修改后的Python字典对象转换回JSON格式的字符串表示。 下面是一个例子,说明如何使用上述函数替换JSON中某个字段的内容: ```python # 原始的JSON数据 json_data = '{"name" : "Tom", "age" : 25, "city" : "New York"}' # 替换字段 new_json = replace_json_field(json_data, "age", 30) print(new_json) ``` 输出结果为: ``` {"name": "Tom", "age": 30, "city": "New York"} ``` 在这个示例中,我们将原始JSON数据中的`age`字段的从25替换为30。 ### 回答3: 要替换JSON中的某个字段内容,可以使用Python中的json库来实现。下面是一个示例代码: ```python import json # 原始JSON数据 json_data = ''' { "name": "John", "age": 30, "city": "New York" } ''' # 将JSON数据转换为字典 data = json.loads(json_data) # 替换"city"字段的内容为"Los Angeles" data["city"] = "Los Angeles" # 将修改后的字典转换为JSON字符串 new_json_data = json.dumps(data) print(new_json_data) ``` 运行以上代码,输出结果为: ```plaintext {"name": "John", "age": 30, "city": "Los Angeles"} ``` 可以看到,成功将JSON中的"city"字段从"New York"替换为"Los Angeles"。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值