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

如何将大型JSON文件中所有属性值替换为同一字符串?

批量替换JSON所有属性值为指定字符串

需求说明

将大型JSON文件中所有属性的值统一替换为同一个字符串,比如把示例里的"some text1"、"some text2"等全部替换为"hello"。

实现方法(Python脚本)

处理大型JSON文件用Python高效且易操作,以下是完整脚本:

import json

# 配置参数
input_file = "your_input.json"  # 替换为你的输入JSON文件路径
output_file = "your_output.json"  # 替换为输出文件路径
target_str = "hello"  # 要替换成的目标字符串

# 读取JSON文件
with open(input_file, "r", encoding="utf-8") as f:
    data = json.load(f)

# 遍历所有键,替换值
for key in data:
    data[key] = target_str

# 写入新的JSON文件
with open(output_file, "w", encoding="utf-8") as f:
    json.dump(data, f, indent=2, ensure_ascii=False)

脚本说明

  • 用json.load把JSON文件内容读取为字典对象
  • 循环遍历字典的每个键,将对应的值设置为目标字符串
  • 用json.dump将修改后的字典写入新文件,indent=2保证输出格式和示例一致,ensure_ascii=False避免中文乱码(有中文需求时适用)

示例验证

输入JSON(修正语法错误后):

{
 "example1": "some text1",
 "example2": "some text2",
 "example3": "some text3"
}

执行脚本后输出:

{
  "example1": "hello",
  "example2": "hello",
  "example3": "hello"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 14:05:56