修复Node.js fs替换JSON值时的null问题并实现多字段替换
问题修复:保留test.json原有内容并替换指定字段值
问题根源
- map遍历导致null值:你用
map处理data.data时,仅对type == "s3 credentials"的项返回了新对象,其他项无返回值,map会自动将这些无返回的项转为null。 - 丢失原有字段:写入文件时直接生成仅含
data的新对象,丢弃了test.json中原有的label等字段。 - 未处理全量占位符:未实现
access、key、path、bucketPath这些占位符的替换逻辑。
修复后的完整代码
const fs = require("fs").promises; async function readJSON(filePath) { const data = await fs.readFile(filePath); try { return JSON.parse(data); } catch (err) { console.error(err); throw err; } } (async () => { try { // 读取配置文件并解构所需字段 const credentials = await readJSON("./configuration.json"); const { key, access, path, bucket, bucketPath } = credentials; // 读取test.json的完整内容 const testData = await readJSON("./test.json"); // 遍历处理每个data项 const updatedData = testData.data.map(item => { switch (item.type) { case "config": // 替换access和key的占位符 return { ...item, values: { access, key } }; case "s3 credentials": // 覆盖bucket字段值 return { ...item, bucket }; case "upload": // 替换input中的$path占位符 return { ...item, input: item.input.replace("$path", path) }; case "change": // 替换measure中的$bucketPath占位符 const updatedMeasure = item.measure.map(measure => measure.to ? { ...measure, to: measure.to.replace("$bucketPath", bucketPath) } : measure ); return { ...item, measure: updatedMeasure }; default: // 其他类型直接返回原对象,保留所有原有内容 return item; } }); // 保留test.json原有所有字段,仅更新data部分 const finalJSON = { ...testData, data: updatedData }; // 写入文件并添加缩进,保证JSON格式美观 await fs.writeFile("./test.json", JSON.stringify(finalJSON, null, 2)); console.log("文件更新完成"); } catch (err) { console.error("处理失败:", err); } })();
关键修复点说明
- 解决null值问题:
map遍历每个item时,所有分支都返回对应对象,默认分支直接返回原item,避免无返回值导致的null。 - 保留原有字段:用
...testData扩展test.json的所有原有字段(如label),仅替换需要更新的data数组,不会丢失任何原有内容。 - 全量替换占位符:针对不同
type的item做针对性处理,覆盖或替换对应的字段和占位符。 - 错误处理优化:读取文件出错时抛出错误,主逻辑用try-catch包裹,便于排查问题。
修复后的test.json效果
{ "label": "storage record", "data": [ { "id": "8902uw", "type": "config", "values": { "access": "793082", "key": "880082" } }, { "id": "893wh002jei", "type": "s3 credentials", "bucket": "testBucket" }, { "id": "90yueps", "type": "upload", "input": "localhost: `/store`" }, { "id": "9028901", "type": "change", "name": "Adjust data", "measure": [ { "t": "setter" }, { "p": "filename", "to": "$join([\"/record\", data])" } ], "fixed": "" } ] }
内容的提问来源于stack exchange,提问作者Didi
相关产品推荐
相关产品推荐

