Codementor Events

How to Use JSON files in Node.js

Published May 21, 2015Last updated Jun 08, 2017
How to Use JSON files in Node.js

Node.js has emerged as a leading platform for creating fully scalable applications within least amount of time. Additionally, the platform undergoes constant upgrades so as to allow developers to continue delivering bespoke applications for their clients. Unlike in the case of XML, choosing JSON files for storing data is a convenient option. The reason being that the JSON files are less cluttered and easy-to-read. Collaborating JSON files with Node.js makes it simple to ensure that the information can be easily accessed by the users. Continue going through this post to learn the method of using JSON files in Node.js.

What is JSON?

Before proceeding ahead, let me brief you on what exactly is JSON (JavaScript Object Notation). Well, it is basically a lightweight data format which has become a web standard followed by a majority of web developers across the globe. JSON can either be represented as a hash of properties and values(for e.g. an Object) or as a list of values (for e.g. an Array).
Have a look at this:

// a JSON array
["nine", "ten", "eleven"]
// a JSON object
{ "nine": 9, "ten": 10, "eleven": 11 }

Handling JSON Files in Node.js

Step 1

Create a dummy JSON file:

{
  "username":"xyz",
  "password":"xyz@123",
  "email":"xyz@xyz.com",
  "uid": 1100
}

Save the above JSON file as dummy.json.
After this, save the same file as demo.txt.

Step 2

Decide whether you want to go in for the synchronous or asynchronous method of reading the above created JSON file.

Talking about synchronous method of reading a JSON file, it basically refers to one-way execution wherein there is a single flow which executes the JSON file line by line. The file will move to the next statement only after the statement has completed. As compared to synchronous call, in an asynchronous call, the flow-control will move to the next line by displaying the concerns over the statement's completion. While synchronous is also referred to as blocking calls, asynchronous refers to non-blocking calls.

Step 3

Depending upon your selection of the method for reading the JSON file, the outputs would vary.

The code for synchronous call will be displayed like this:

// Read Synchrously
var fs = require("fs");
console.log("\n *START* \n");
var content = fs.readFileSync("content.txt");
console.log("Output Content : \n"+ content);
console.log("\n *EXIT* \n");

Also, the synchronous output (single-flow) will be displayed like this:

D:\NodeJs>node readsync.js
 *START*
Output Content:
 /* content here */
*EXIT*
// Define JSON File
 var fs = require("fs");
 console.log("\n *STARTING* \n");
// Get content from file
 var contents = fs.readFileSync("jsoncontent.json");
// Define to JSON type
 var jsonContent = JSON.parse(contents);
// Get Value from JSON
 console.log("User Name:", jsonContent.username);
 console.log("Email:", jsonContent.email);
 console.log("Password:", jsonContent.password);
log("\n *EXIT* \n");

Now, the final output will be like this:

D:\NodeJs>node readjson.js
*STARTING*
User Name: xyz
 Email: xyz@xyz.com
 Password: xyz@123
*EXIT*

Here's a look at some common operations that can be performed for a JSON object in Node.js:

Converting a JSON object to a String

You can opt for the 'stringify' method for converting the JSON object into a string data as shown below:

var obj = {'key':'value'};
console.log(
    /* define stringify */
    JSON.stringify(obj)
);

Converting a String to a JSON object

The code associated with using the built-in global JSON Object for parsing a string containing JSON data is shown below:

var string = "{'key':'value'}";
var obj = JSON.parse(string);
 console.log(obj.key);

As an alternative, you can also use the “trim()” method available on the string. This works under a situation when there are some chances of having any extra space within the JSON string.

Automatically Reading a JSON file

The code which can be used for making Node.js automatically read the JSON file is shown below:

var obj = require("../path/jsonfile.json");

Here, Node.js will parse the content to a particular JSON object and assign the same to the variable placed on the left hand side.

Adding a New Element to an existing JSON Object

For instance, you already have a JSON object and you're interested in modifying it by adding a new key/value pair(). You can do the same in either of the two ways shown below:

var exjson = {'key':'value'};
//define key value
 exjson.key2 = '...abc...';
//define another key value
 exjson[key3] = '...xyz...';

Traversing through each element within a JSON object

If you're interested in traversing through each and every element within the JSON object, then the same can be done using a 'for' loop as explained in the code snippet:

var exjson = {'key':'...abc...', 'key2':'...xyz...'};
for(var exKey in exjson) {
    console.log("key:"+exKey+", value:"+exjson[exKey]);
}

Here, do note that the above code can give you an error if the value is the JSON Object itself. Hence, it is recommended to check whether the value is JSON or not. Once you're certain about this, you can proceed ahead to handling the JSON object.

Checking whether the JSON object has a specific key

If you're required to check whether the JSON object has a specific key or not, you can do the same using the below mentioned code snippet:

var exjson = {'key':'...abc...', 'key2':'...xyz...'};
if(exjson.hasOwnProperty('key2')){
    //define here
}

Deleting an element from the JSON Object

You can use the 'delete' keyword for selecting an element from a particular JSON Object as explained in below example:

var exjson = {'key':'...abc...'};
 delete exjson['key'];

That's it for now!

Conclusion

Here's hoping the above post would allow you to get into the details of using JSON files in Node.js. So, do keep it as a reference for all your forthcoming web development projects.


About the Author:

Rick Brown is a programmer who has helped companies gain momentum with their small and large scale projects. If you need to iPhone app developer for hire then simply get in touch with Rick via Twitter. He is currently working for Mobiers Ltd., a leading mobile app development company.

Discover and read more posts from Codementor Team
get started
post commentsBe the first to share your opinion
Greg Venezia
6 years ago

How do you write json back to the file?

Luis Marroquin
5 years ago

fs.writeFile

Bang Andre
6 years ago

Thank you very much your tutorial

Hender R
7 years ago

This article was so helpful to me but only i want to add some case no exactly to what you show here.
What if the json file contains an array of objects such as:
[
{
“username”:“xz”,
“password”:“xz@123”,
email":"xyz@xz.com”,
“uid”: 1100
},
{
“username”:“yz”,
“password”:“yz@123”,
email":"xyz@yz.com”,
“uid”: 1200
}
]

then I did solve so:

var contents = fs.readFileSync(“someJsonFile.json”);
var objsArray = []
objsArray = JSON.parse(contents);

console.log("username1: " + objsArray[0].username);
console.log("username2: " + objsArray[1].username);

username1: xz
username2: yz

Thanks very much.

Southern Wolf 🐺
7 years ago

This worked beautifully for the problem I was having! Thanks for sharing! <3

Show more replies