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
- 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?