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
- Why Laravel does not optimize model queries automatically?
- Why are RDBMS'es CS systems in the CAP sense according to this graphic?
- How to create a Local Database in Android?
- Which is better SQL database or json file?
- Check for changes to an SQL Server table?
- What are the actual types of database indexes?
- How does a DBMS implement their own sorting algorithm? Or do they?