【问题标题】:Write data to empty json file将数据写入空的 json 文件
【发布时间】:2019-10-01 17:02:33
【问题描述】:

首先我在第一次运行之前截断 json 文件。

对于之后的每次运行,我都想继续附加到 json 文件中。第一次运行,因为数据为空,我得到 'SyntaxError: Unexpected end of JSON input'

    public jsondata = (newdata: string) => {

    var fs = require('fs');

    fs.readFile('output.json', function (err, data) {

       let json:any = [];
            console.log('some data =' + data + '=');

            if(data === '') {
            json = JSON.parse(newdata);
            json.push(newdata);
            }
            else {
            json = JSON.parse(data);
            json.push(newdata);
            }

        fs.writeFile('output.json', JSON.stringify(json, null, 4), (err) => {
            if (err) throw err;
            console.log('The json file has been saved');
        });
    });
}

【问题讨论】:

    标签: javascript json typescript


    【解决方案1】:
    fs.readFile('output.json', 'utf-8', function (err, data) { 
        if (data === '') {
            json.push(newdata);
        }
    

    代替

    fs.readFile('output.json', function (err, data) {
        if(data === '') {
            json = JSON.parse(newdata);
            json.push(newdata);
        }
    

    为什么:

    如果output.json 为空
    来自fs.readFile('output.json', function (err, data) { ... })data<Buffer > 而不是 ''(空字符串)
    因此,使用您的代码,if (data === '') 始终是 false
    json = JSON.parse(data) 生成 SyntaxError: Unexpected end of JSON input

    【讨论】:

      猜你喜欢
      • 2018-05-26
      • 1970-01-01
      • 1970-01-01
      • 2014-08-14
      • 2012-08-31
      相关资源
      最近更新 更多