You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python更新嵌套JSON文件中所有层级的旧域名

解决多层嵌套JSON中批量替换域名的问题

你当前的代码仅能处理固定两层嵌套的layers结构,无法覆盖JSON内任意深层的url字段。要实现全层级的域名替换,需要用递归遍历的方式,自动识别所有嵌套的字典和列表,找到目标字段完成替换。

完整实现代码

import json

old_url = 'https://olddomain.co.uk/arcgis'
new_url = 'https://newdomain.co.uk/server'
target_key = 'url'

def replace_domain(obj):
    # 处理字典类型:遍历所有键值对
    if isinstance(obj, dict):
        for key, value in obj.items():
            # 找到目标key且值为包含旧域名的字符串时替换
            if key == target_key and isinstance(value, str) and old_url in value:
                obj[key] = value.replace(old_url, new_url)
            # 递归处理嵌套的子对象
            replace_domain(value)
    # 处理列表类型:遍历每个元素递归处理
    elif isinstance(obj, list):
        for item in obj:
            replace_domain(item)

# 读取原始JSON文件
with open('your_webmap.json', 'r', encoding='utf-8') as f:
    webmap_data = json.load(f)

# 执行全层级域名替换
replace_domain(webmap_data)

# 保存修改后的JSON文件
with open('updated_webmap.json', 'w', encoding='utf-8') as f:
    json.dump(webmap_data, f, indent=4)

代码说明

  • 递归函数replace_domain会自动识别JSON中的字典和列表结构:
    • 遇到字典时,检查每个键是否为目标url,符合条件则替换域名;同时递归处理每个键对应的值,确保深层嵌套的结构也能被遍历到
    • 遇到列表时,逐个遍历列表元素并递归处理,覆盖所有嵌套在列表中的子结构
  • 不管url字段在JSON的哪一层嵌套(比如多层layers嵌套、其他字段下的嵌套),都能被精准找到并替换

内容的提问来源于stack exchange,提问作者sunsilk85

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 19:52:44