NodeJS如何统一替换JSON文件中指定键所有层级的对应值
解决方案
核心原理是通过递归遍历JSON对象的所有嵌套层级,匹配到指定键名时统一替换为目标值。
核心替换函数
// 入参分别为:要处理的对象、目标键名、要替换的新值 function replaceKeyRecursively(obj, targetKey, newValue) { for (const key in obj) { // 匹配到目标键直接替换值 if (key === targetKey) { obj[key] = newValue; } // 如果当前属性值是对象/数组,递归进入处理内部内容 if (typeof obj[key] === 'object' && obj[key] !== null) { replaceKeyRecursively(obj[key], targetKey, newValue); } } }
完整可运行代码
直接替换你原来的代码即可,按需修改顶部的三个配置项:
const fs = require('fs'); // ========== 配置项开始 可根据需求修改 ========== const Profile = '你的JSON文件名(不需要后缀)'; const targetKey = 'Level'; // 要替换的键名 const replaceValue = 'C'; // 替换后的固定值 // ========== 配置项结束 ========== function replaceKeyRecursively(obj, targetKey, newValue) { for (const key in obj) { if (key === targetKey) { obj[key] = newValue; } if (typeof obj[key] === 'object' && obj[key] !== null) { replaceKeyRecursively(obj[key], targetKey, newValue); } } } const fileName = `./${Profile}.json`; const fileContent = require(fileName); // 执行全层级替换 replaceKeyRecursively(fileContent, targetKey, replaceValue); // 写入修改后的内容到原文件 fs.writeFile(fileName, JSON.stringify(fileContent, null, 2), (error) => { if (error) return console.log('写入失败:', error); console.log('所有匹配键值替换完成'); });
注意事项
- 该方案兼容包含数组的JSON结构,数组内部嵌套对象的目标键也会被正常替换
- 常规业务场景的JSON不存在循环引用,无需担心递归栈溢出问题
- 如果要保留原文件,可修改
fs.writeFile的第一个参数为新的文件名,避免覆盖原文件
内容的提问来源于stack exchange,提问作者indust0x0000000f
相关产品推荐
相关产品推荐

