append to a json file in javascript

To append data to a JSON file in JavaScript, you can use the fs module that comes with Node.js. Here's an example code snippet that demonstrates how to do this:

index.tsx
const fs = require('fs');

const newData = {
    name: 'John Doe',
    email: 'johndoe@example.com',
    age: 28
};

fs.readFile('data.json', 'utf8', (err, data) => {
    if (err) {
        console.error(err);
        return;
    }

    const json = JSON.parse(data);
    json.push(newData);

    fs.writeFile('data.json', JSON.stringify(json), (err) => {
        if (err) {
            console.error(err);
            return;
        }
        console.log('Data appended to file successfully!');
    });
});
509 chars
26 lines

In this example, we first read the JSON data from the file using readFile() function. We then parse the data into a JavaScript object using JSON.parse().

After that, we append the new data to the object using push() function.

Finally, we overwrite the original file with the updated JSON data using writeFile() function. We pass the JSON.stringify() function to writeFile() to convert the object back to a JSON string before writing to the file.

Note: This code assumes that data.json file already exists and has valid JSON data inside it.

gistlibby LogSnag