从文件修改 json 对象并保持结构

Modify json object from file and keep structure

我们有一个 json 对象如下

JSON之前

// comment 1
{
    "version": "2.0.0",
    "tasks": [{
        "type": "task1",
        "script": "watch",
        "problemMatcher": "$tsc-watch",
        "isBackground": true,
        "presentation": {
            "aaa": "never"
        }
    }]
}
// comment 2

JSON 之后

现在我想添加一个新对象一个新任务(任务 2)

// comment 1
{
    "version": "2.0.0",
    "tasks": [{
            "type": "task1",
            "script": "watch",
            "problemMatcher": "$tsc-watch",
            "isBackground": true,
            "presentation": {
                "aaa": "never"
            }
        },

        {
            "type": "task2",
            "script": "watch",
            "problemMatcher": "$tsh",
            "isBackground": true,
            "presentation": {
                "aaa": "never"
            }
        }
    ]
}

// comment 2

这里的技巧是,我需要更新对象 而不 更改结构、行或注释。我尝试使用 jsonParse 但它不起作用

在 javascript/nodejs 中可以吗?

我建议查看 comment-json 包,这是它的设计目的,您不需要为此推出自己的包。

您可以解析 JSON,然后添加新任务并写入您的新文件:

const { parse, stringify} = require("comment-json");
const fs = require("fs");

const taskFile = parse(fs.readFileSync("./input.json", "utf8"));

let taskToAdd = {
  "type": "task2",
  "script": "watch",
  "problemMatcher": "$tsc-watch",
  "isBackground": true,
  "presentation": {
      "aaa": "never" 
  }
};

taskFile.tasks.push(taskToAdd);
fs.writeFileSync("./output.json", stringify(taskFile, null, 4));

input.json

// comment 1
{
    "version": "2.0.0",
    "tasks": [{
        "type": "task1",
        "script": "watch",
        "problemMatcher": "$tsc-watch",
        "isBackground": true,
        "presentation": {
            "aaa": "never"
        }
    }]
}
// comment 2

当然,如果您想就地修改 JSON 文件,只需将输入和输出文件名设置为相同的值即可。