如何在Python中用正则表达式替换JSON中的指定URL片段
解决JSON中特定URL的替换问题
方法1:解析JSON字典处理(更安全)
这种方法先把JSON解析为Python字典,针对性处理每个值,避免破坏JSON结构:
import json import re # 读取目标JSON文件 with open('target.json', 'r', encoding='utf-8') as f: json_data = json.load(f) # 定义匹配规则和替换模板 match_pattern = r'(https://)foo(\.bar\.com/x/)env_t(/.*)' replace_str = r'\1fooa\2env_a\3' # 遍历字典,处理符合格式的URL for key, val in json_data.items(): if isinstance(val, str) and re.match(r'https://foo\.bar\.com/x/env_t/', val): json_data[key] = re.sub(match_pattern, replace_str, val) # 写入修改后的JSON with open('modified_target.json', 'w', encoding='utf-8') as f: json.dump(json_data, f, indent=2)
方法2:直接对JSON字符串正则替换
如果不想解析字典,也可以直接对JSON字符串做替换,注意正则要精准匹配目标URL:
import re # 读取JSON内容(或从文件读取) raw_json = '''{ "a_url": "https://foo.bar.com/x/env_t/xyz?asd=dfg", "b_url": "https://foo.bar.com/x/env_t/xyz?asd=dfg", "some other property": "blabla", "more stuff": "yep", "c_url": "https://blabla.com/somethingsomething?maybe=yes" }''' # 正则匹配目标URL并替换 pattern = r'(https://)foo(\.bar\.com/x/)env_t(/[^"]+)' modified_json = re.sub(pattern, r'\1fooa\2env_a\3', raw_json) # 输出或保存结果 print(modified_json)
正则说明
- 分组
\1捕获https://,\2捕获.bar.com/x/,\3捕获env_t之后到引号前的所有内容 - 替换时仅修改
foo为fooa、env_t为env_a,其余部分保持不变 - 原正则中的
\"是HTML转义的引号,在Python中无需保留,调整后的正则更精准,不会误匹配其他内容
内容的提问来源于stack exchange,提问作者Leon Cullens
相关产品推荐
相关产品推荐

