[英]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));
输入.json
// comment 1
{
"version": "2.0.0",
"tasks": [{
"type": "task1",
"script": "watch",
"problemMatcher": "$tsc-watch",
"isBackground": true,
"presentation": {
"aaa": "never"
}
}]
}
// comment 2
当然,如果您希望就地修改 JSON 文件,只需将输入和输出文件名设置为相同的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.