How to write javascript object in to JSON file

Write javascript object to filesystem as JSON file

Suppose you want to write javascript object in to file system as JSON file

const database = {
    "id": 1
    "name": "CodeRecharge.",
    "likes": 12,
    "visits": 1000
}

we will use NodeJS to perform write opentation.

// import
const fs = require("fs");

// Js Object
const database = {
    "id": 1
    "name": "CodeRecharge.",
    "likes": 12,
    "visits": 1000
}

// Write as JSON
fs.writeFileSync("./database.json", JSON.stringify(database, null, 2));

Above code will create database.json file in current directory and write database objec content in to the database.json file as JSON notation.

Notice that we are using JSON.stringify function as file can only hole string values. so first we need to convert javascript object in to string using JSON.stringify.

Once we have equivalent string of our javascript object we can save it to the filesystem.

You can check out whole flat file databse read and write article:JSON as flat file database

Related Articles

js interview questions