【问题标题】:I have a json file and I want to add new field to it我有一个 json 文件,我想向它添加新字段
【发布时间】:2021-04-17 03:44:47
【问题描述】:

我有一个 json 文件

[{
    "sport": "football",
},
{
    "sport": "swimming",
}]

我想为每个文档添加一个新字段,一个 uniqueID 字段,其格式为 A-11,并将每个对象的数字加一

我已经在 Node 中尝试过这个

const fs = require('fs');
const filenameAppo = './app.json';
const requireFile = require(filenameAppo);

requireFile.uniqueID = 'A-11';
const test = fs.writeFile(filenameAppo,JSON.stringify(requireFile), function(err) {
    if (err) return console.log(err);

});

但它没有按预期工作,所以我的错误是什么,或者如果我有其他方法可以做到这一点

【问题讨论】:

    标签: node.js express fs


    【解决方案1】:

    我认为解决这个问题的最佳方法是为文件数组数据创建一个对象包装器,然后添加 uniqueID 属性,如下所示:

    const fs = require('fs');
    const filenameAppo = './app.json';
    const requireFile = require(filenameAppo);
    
    const inputData = requireFile.data || requireFile;
    let id = 11;
    const output = { 
        data: inputData.map(row => { 
            row.uniqueID = "A-" + (id++);
            return row;
        }) 
    }
    
    const outputString = JSON.stringify(output , null, 4);
    console.log(`Writing ${outputString.length} bytes to file: ${filenameAppo}...`);
    fs.writeFile(filenameAppo, JSON.stringify(output , null, 4), function(err) {
        if (err) { 
            console.error(`An error occurred writing output file: ${filenameAppo}:`, err);
        } else { 
            console.log(`Successfully wrote ${outputString.length} bytes to file: ${filenameAppo}.`)
        }
    });
    

    您的 app.json 文件将如下所示:

    {
        "data": [
            {
                "sport": "football",
                "uniqueID": "A-11"
            },
            {
                "sport": "swimming",
                "uniqueID": "A-12"
            }
        ]
    }
    

    【讨论】:

    • 我希望它是这样的 { "data": [ { "sport": "football", "uniqueID": "A-11" }, { "sport": "swimming", "uniqueID": "A-12" } ], } 因为每个文档都必须有唯一的 id
    • 我已经尝试过了,所以首先我在 express 上调用我的文件以在服务器像这样运行时启动 require('../dbDataHolder/init');然后我使用您在评论中使用的代码,但更改未保存在文件中
    • Hmmm.. 代码可能没有运行或者我们可能会遇到错误,您可以尝试更新代码并查看是否显示任何日志消息吗?
    • 它在终端中向我显示此消息已成功将 2141 字节写入文件:./test.json。问题是更改未保存
    • 这很奇怪,如果我们无法访问该文件,我们通常会得到一个错误。是否有其他进程也在更新它?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-17
    • 1970-01-01
    • 2019-10-19
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多