const fs = require('fs')
const path = require('path')
const { parse, applyEdits, modify } = require('jsonc-parser');

// 定义文件路径
const manifestPath = path.resolve(__dirname, '../src/manifest.json');
// 读取 JSON 文件内容
const fileContent = fs.readFileSync(manifestPath, 'utf8');
// 解析 JSON 文件(包括注释)
let data = parse(fileContent);

// 检查目标路径是否存在
if (data['mp-weixin'] && data['mp-weixin']['appid']) {
  // 定义新值
    const newAppid = "wx80f8550b39a13547";
    // 定义格式化选项(2个空格缩进)
    const formattingOptions = {
        insertSpaces: true,
        tabSize: 2,
    };
    // 生成修改操作的变更列表
    const edits = modify(fileContent, ['mp-weixin', 'appid'], newAppid,{ formattingOptions });
    // 应用变更
    const updatedContent = applyEdits(fileContent, edits);
    // 写回文件
    fs.writeFileSync(manifestPath, updatedContent, 'utf8');
    console.log('manifest.json 文件已更新');
    } else {
    console.error('目标路径 mp-weixin.appid 不存在');
    }

或者使用comment-json

const fs = require('fs');
const path = require('path');
const commentJson = require('comment-json');

// 定义文件路径
const manifestPath = path.resolve(__dirname, '../src/manifest.json');

// 读取 JSON 文件内容(包括注释)
let fileContent = fs.readFileSync(manifestPath, 'utf8');

// 解析带注释的 JSON
let json = commentJson.parse(fileContent);

// 修改目标值
if (json['mp-weixin'] && json['mp-weixin']['appid']) {
  // 修改 appid 的值
  json['mp-weixin'].appid = 'new_appid_value';
}

// 将修改后的对象转换回带注释的 JSON 格式
const updatedContent = commentJson.stringify(json, null, 2);

// 将修改后的内容写回文件
fs.writeFileSync(manifestPath, updatedContent, 'utf8');
console.log('manifest.json 文件已更新');

如果更改后文件不需要保留注释的话,也可以用json5

const fs = require('fs');
const JSON5 = require('json5');

// 读取 JSON5 文件
const filePath = './config.json5';
const jsonWithComments = fs.readFileSync(filePath, 'utf8');

// 解析 JSON5 文件
let json = JSON5.parse(jsonWithComments);

// 修改数据
json.key1 = "newValue1"; // 修改键值
json.key3 = "value3";    // 添加新键值对

// 将对象转换回 JSON5 格式(保留注释和格式)
const updatedJson = JSON5.stringify(json, null, 2); // 美化输出,2 表示缩进

// 写回文件
fs.writeFileSync(filePath, updatedJson, 'utf8');
console.log('JSON5 文件已更新');

Last Updated:
Contributors: haizhiguang