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

如何修改读取的JSON文件中指定值且保留其他字段不改动

JavaScript读取JSON文件并修改指定字段的实现

需求说明

需要读取本地JSON配置文件,仅修改3个字段中的2个,保留最后一个字段的原有值不变。以下是最初编写的问题代码:

const fs = require('fs-extra');
const config_json  = __dirname + "\\config.json"
const args = require('minimist')(process.argv.slice(2))


var exp_clean = args["clean"]
var exp_asked = args["asked"]
var remove_arg = args["remove"]
if (remove_arg == "") {
    fs.readFile(config_json, 'utf8', (err, data) => {
        if (err) {console.log("error", err)}
        var obj = JSON.stringify(data, null, 4)
        // how do i change values within the read json data?
        // {
        //     "experimental-cleaning": "false",
        //     "experimental-asked": "false",
        //     "to-remove": ""
        // }
        // that is whats in the json file being read
    })
    var obj = {
        "experimental-cleaning": exp_clean,
        "experimental-asked": exp_asked,
        "to-remove": to_remove
    }
    var stringified = JSON.stringify(obj, null, 4)
    fs.writeFile(config_json, stringified, (err) => {
        if (err) {console.log("error", err)}
    })
}
else {var remove_arg}
var obj = {
    "experimental-cleaning": exp_clean,
    "experimental-asked": exp_asked,
    "to-remove": to_remove
}
var stringified = JSON.stringify(obj, null, 4)
fs.writeFile(config_json, stringified, (err) => {
    if (err) {console.log("error", err)}
})

问题代码的错误点

  • 方法调用混淆:JSON.stringify()是将JS对象转为JSON字符串,读取到的JSON字符串需要先用JSON.parse()转为JS对象才能修改内部字段
  • 异步逻辑错误:fs.readFile是异步方法,回调外的写文件逻辑执行时还未读取到原JSON内容,无法保留原有字段
  • 变量未声明:代码中直接使用未定义的to_remove变量,会触发运行时报错
  • 逻辑冗余:存在无判断条件的重复写文件调用,会直接覆盖原配置内容

修复后的正确实现

修复逻辑核心是直接引入JSON文件自动解析为JS对象,保留所有原有字段,仅修改需要更新的字段即可:

const fs = require('fs-extra');
const config = require('.\\config.json')
const args = require('minimist')(process.argv.slice(2))


const exp_clean = `${args["clean"]}`
const exp_asked = `${args["asked"]}`
const remove = `${args["remove"]}`
if (remove == 'undefined') {
    config['experimental-cleaning'] = exp_clean
    config['experimental-asked'] = exp_asked
    config_string = JSON.stringify(config, null, 4)
    fs.writeFile(__dirname + "\\config.json", config_string, (err) => {
        if (err) {console.log("error", err)}
    })
    console.log("config updated")
}
else {
config['experimental-cleaning'] = exp_clean
config['experimental-asked'] = exp_asked
config['to-remove'] = remove
config_string = JSON.stringify(config, null, 4)
fs.writeFile(__dirname + "\\config.json", config_string, (err) => {
    if (err) {console.log("error", err)}
})
console.log("config updated")
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 00:12:04