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

如何用Node.js将values.json的值替换到data.json指定字段中

Node.js 实现JSON字段替换覆盖方案

前提说明

假设你的文件结构示例如下:

  • values.json 内容:
{
  "access": "new-access-token",
  "key": "new-secret-key"
}
  • data.json 常见两种结构(根据你的实际结构选择对应逻辑):
    情况1:单个对象嵌套
    {
      "serviceConfig": {
        "access": "old-access-token",
        "key": "old-secret-key",
        "timeout": 3000
      }
    }
    
    情况2:数组中按类型匹配项
    [
      {
        "type": "external-api",
        "access": "old-access-token",
        "key": "old-secret-key"
      },
      {
        "type": "internal-db",
        "username": "admin"
      }
    ]
    

异步实现方案(推荐,非阻塞)

使用 fs/promises 模块处理文件操作,适合Node.js 14+版本:

const fs = require('fs').promises;
const path = require('path');

async function updateCredentials() {
  try {
    // 读取并解析values.json
    const valuesContent = await fs.readFile(path.join(__dirname, 'values.json'), 'utf8');
    const { access, key } = JSON.parse(valuesContent);

    // 读取并解析data.json
    const dataContent = await fs.readFile(path.join(__dirname, 'data.json'), 'utf8');
    const data = JSON.parse(dataContent);

    // 替换字段 - 根据你的data.json结构选择对应逻辑
    // 情况1:替换单个嵌套对象的字段
    if (data.serviceConfig) {
      data.serviceConfig.access = access;
      data.serviceConfig.key = key;
    }

    // 情况2:替换数组中指定type项的字段
    // if (Array.isArray(data)) {
    //   const targetItem = data.find(item => item.type === 'external-api');
    //   if (targetItem) {
    //     targetItem.access = access;
    //     targetItem.key = key;
    //   }
    // }

    // 将修改后的数据格式化写入data.json
    const updatedData = JSON.stringify(data, null, 2);
    await fs.writeFile(path.join(__dirname, 'data.json'), updatedData, 'utf8');

    console.log('字段替换完成');
  } catch (err) {
    console.error('操作失败:', err.message);
  }
}

// 执行函数
updateCredentials();

同步实现方案(适合简单脚本)

使用 fs 同步方法,代码更简洁但会阻塞线程:

const fs = require('fs');
const path = require('path');

function updateCredentialsSync() {
  try {
    // 读取解析values.json
    const { access, key } = JSON.parse(fs.readFileSync(path.join(__dirname, 'values.json'), 'utf8'));

    // 读取解析data.json
    const data = JSON.parse(fs.readFileSync(path.join(__dirname, 'data.json'), 'utf8'));

    // 替换逻辑(同上,选择对应情况)
    if (data.serviceConfig) {
      data.serviceConfig.access = access;
      data.serviceConfig.key = key;
    }

    // 写入文件
    fs.writeFileSync(path.join(__dirname, 'data.json'), JSON.stringify(data, null, 2), 'utf8');
    console.log('字段替换完成');
  } catch (err) {
    console.error('操作失败:', err.message);
  }
}

updateCredentialsSync();

注意事项

  • 确保两个JSON文件格式合法,否则 JSON.parse 会抛出语法错误
  • 根据你的实际 data.json 结构调整替换逻辑,比如修改对象层级或匹配条件
  • JSON.stringify 的第三个参数(示例中为2)用于格式化输出,保持文件可读性,可省略
  • 若需处理大文件,建议使用流式操作避免内存占用过高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 14:40:35