Node.js如何遍历嵌套JSON替换字符串并生成新对象
解决方案
你可以将递归逻辑调整为每次处理节点都返回对应结构的新值,全程不修改原JSON对象,同时完整保留原嵌套结构,实现代码如下:
const fs = require('fs'); // 读取源JSON文件 const originalObj = JSON.parse(fs.readFileSync('en.json', 'utf-8')); // 替换为你实际的翻译实现,可对接各类翻译API const yourTranslateLogic = (text) => { // 示例为直接返回加标识的文本,实际场景替换为真实翻译逻辑 return `翻译后:${text}`; } // 递归处理对象的核心函数 const processNestedObj = (input, path = '') => { // 处理数组类型 if (Array.isArray(input)) { const newArr = []; for (let i = 0; i < input.length; i++) { const currentPath = path ? `${path}[${i}]` : String(i); newArr.push(processNestedObj(input[i], currentPath)); } return newArr; } // 处理普通对象类型 if (typeof input === 'object' && input !== null) { const newObj = {}; for (const [key, value] of Object.entries(input)) { const currentPath = path ? `${path}.${key}` : key; newObj[key] = processNestedObj(value, currentPath); } return newObj; } // 处理字符串类型:走翻译逻辑 if (typeof input === 'string') { // 可保留你原有的路径打印需求 console.log(`${path} --> 原文本:${input}`); return yourTranslateLogic(input); } // 数字、布尔、null等非字符串类型直接返回原值,不破坏结构 return input; } // 执行处理并写入结果文件 const translatedObj = processNestedObj(originalObj); fs.writeFileSync('zh.json', JSON.stringify(translatedObj, null, 2), 'utf-8'); console.log('翻译完成,结果已保存至zh.json');
补充说明
- 代码兼容普通对象、数组的任意层级嵌套场景,不会修改源文件结构
- 如果你需要调用异步翻译API,只需要给核心函数加
async/await修饰即可 - 不需要路径打印的话,删除对应console.log和path传参逻辑即可,运行效率更高
内容的提问来源于stack exchange,提问作者nick
相关产品推荐
相关产品推荐

