【问题标题】:Modify json object from file and keep structure从文件修改json对象并保持结构
【发布时间】:2020-07-07 03:04:25
【问题描述】:

我们有一个带有如下对象的 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 中可以吗?

【问题讨论】:

    标签: javascript node.js json typescript abstract-syntax-tree


    【解决方案1】:

    我建议查看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 文件,只需将输入和输出文件名设置为相同的值即可。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-19
      • 2022-08-03
      • 1970-01-01
      • 1970-01-01
      • 2018-02-11
      • 1970-01-01
      • 2012-02-26
      • 1970-01-01
      相关资源
      最近更新 更多