How to read javascript object in to JSON file

Read javascript object from filesystem as JSON file

Suppose you want to read javascript object from the file system as JSON file.

databse.json file content shown as below

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

we will use NodeJS to perform read opentation.

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

// read
const fileContents = fs.readFileSync("./database.json", "utf8");

// parse
const databaseObject = JSON.parse(fileContents);

// use
console.log(databaseObject.name); // output : CodeRecharge.

Above code will read database.json file from current directory and transfer its content to the fileContent.

Still its not yes correctly parsed as its just string. Now we need to parse it using JSON.parse.So string values can convert from string to javascript object.

After JSON.prase we can use databaseObject as javascript object and use its values.

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

Related Articles

js interview questions