mohamed nageh
mohamed nageh

Reputation: 733

I have a json file and I want to add new field to it

I have a json file

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

I want to add a new field to each document a uniqueID field which have this form A-11 and increase the number by one for each object

I have tried this in 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);

});

But it didn't work as expected so what is my error in that or if there is another way I can do it

Upvotes: 0

Views: 42

Answers (1)

Terry Lennox
Terry Lennox

Reputation: 30705

I believe the best way to approach this is to create an object wrapper for the file array data, then add the uniqueID property, something like this:

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}.`)
    }
});

You app.json file will then look like so:

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

Upvotes: 1

Related Questions