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

如何使用modify-json-file库以字符串变量作为键修改JSON文件

解决方案

基于modify-json-file库的核心实现

要实现用字符串变量指定JSON键,直接使用ES6计算属性名语法即可,这是JavaScript原生支持的特性,能完美适配modify-json-file的API:

let key = "name";
await modifyJsonFile(
    './filename',
    {
        [key]: "kevin" // 用方括号包裹变量,将变量值作为对象键
    }
)

原理:当你用[key]作为对象属性名时,JavaScript会将变量key的实际值(这里是"name")作为最终的属性键,而不是把字符串"key"当作键,效果和直接写name: "kevin"完全一致。

如果需要修改嵌套的JSON属性,同样可以用变量存储路径字符串:

let key = "user.profile.nickname";
await modifyJsonFile(
    './filename',
    {
        [key]: "kevin"
    }
)

其他可选方案(基于fs模块)

若需要脱离第三方库实现,可直接使用Node.js内置的fs/promises模块:

const fs = require('fs/promises');

async function updateJsonFile() {
    const filePath = './filename';
    // 读取并解析JSON文件
    const jsonContent = await fs.readFile(filePath, 'utf8');
    const jsonObj = JSON.parse(jsonContent);
    
    // 用变量指定键并修改值
    const key = "name";
    jsonObj[key] = "kevin";
    
    // 写入修改后的内容(保留缩进格式)
    await fs.writeFile(filePath, JSON.stringify(jsonObj, null, 2));
}

// 调用函数
updateJsonFile();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 15:34:56