Javascript 从文件中修改json对象并保留结构

Javascript 从文件中修改json对象并保留结构,javascript,node.js,json,typescript,abstract-syntax-tree,Javascript,Node.js,Json,Typescript,Abstract Syntax Tree,我们有一个json,其对象如下 之前的JSON // comment 1 { "version": "2.0.0", "tasks": [{ "type": "task1", "script": "watch", "problemMatcher": "$tsc-watch", "isBackground": true, "presentation": { "aaa": "nev

我们有一个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)

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


在javascript/nodejs中可能吗

我建议你去看看这个软件包,这就是它的设计目的,你不需要自己动手

您可以解析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文件,只需将输入和输出文件名设置为相同的值

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