Node.js has proved to be a leading platform which one can use to create very scalable apps in the shortest amount of time possible. The good thing about the platform is that it is upgraded continually to ensure that programmers deliver the best applications to the clients. It is advisable for one to choose JSON files for storage of data other than XML files. This is because JSON files are easy to read and less cluttered. When JSON files are used with Node.js, the developers will find it easy to access them.

Consider the code given below, which is an example of JSON data:

// an array in JSON 
["nine", "ten", "eleven"] 

// an object in JSON 
{ "nine": 9, "ten": 10, "eleven": 11 }

In JSON, data can be stored in the form of a list of values or as a hash of values and properties.

The following are the steps for us to handle JSON files in Node.JS:

The first step should involve creation of a dummy JSON file. This is shown in the code given below:

{ 

    "username":"user1", 
    "password":"user1password" 
    "email":"user1@example.com", 
    "uid": 1100 

}

The above file can be saved and given the name “dymmy.json” The same file should also be saved as “sample.txt”.

You should then come up with a decision as to whether to read the file synchronously or asynchronously. When we talk of the synchronous method, the JSON file will be read in one-way, line-by-line. This means that a line will only be read after the previous one has been read. When it comes to reading asynchronously, the program will move to the next line once it has displayed all of the concerns which it has about the current line.

The output will vary, depending on the method that you use for reading the JSON file. Consider the code given below, which shows the output for a synchronous call:

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

The synchronous output will be displayed as shown below:

C:\NodeJs>node readsync.js 
*STARTING* 
Output Content: 
/* content here */ 
*EXIT* 

// Defining the JSON File 
var files = require("fs"); 
console.log("\n *STARTING* \n"); 

// Getting the content from the file 
var conts = fs.readFileSync("jsoncontent.json"); 

// Definition to the JSON type 
var jsonCont = JSON.parse(conts);

// Getting the Value from the JSON 
console.log("User Name:", jsonCont.username); 
console.log("Email:", jsonCont.email); 
console.log("Password:", jsonCont.password); 
log("\n *EXIT* \n");

The final output should then be as shown below:

C:\NodeJs>node readjson.js 
*STARTING* 
User Name: user1 
Email: user1@example.com 
Password: user1password 
*EXIT*

We now need to explore some of the common operations which can be done to a JSON file in Node.js.

How to Convert a JSON Object to a String

The “stringify” method can be used for the purpose of converting a JSON object to a string. The following code can be used for doing this:

var object = {'key':'value'}; 
console.log( 
    /* defining the stringify */ 
    JSON.stringify(object) 
);

How to convert a String to a JSON Object

The code given below can be used for the purpose of accomplishing this:

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

The “trim(),” which is available for strings can also be used as an alternative to this.

For a JSON file to be read automatically, this can be done as follows:

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

With the above code, the Node.js will be able to automatically read a JSON file. What happens is that the content will be parsed to a particular JSON object, and then this is assigned to a variable.

Addition of a New Element to a JSON Object

Suppose that you have a JSON object, and you are in need of modifying it by addition of a new element to it in the form of a key/value pair. The two ways shown below can be used for the purpose of doing this:

var ejson = {'key':'value'}; 
//defining the key value 
ejson.key2 = '...xyz...'; 
//defining another key value 
ejson[key3] = '...pqr...';

Sometimes, you might be in need of traversing through each object in JSON. For this purpose, one can make use of the “for” loop. This is demonstrated in the code snippet given below:

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

If the above value is used as the JSON object itself, then one can get an error as a result of this. This is why you are encouraged to check on whether this is a JSON object or not. It is after you are certain of it that you can proceed to handle the JSON object.

Sometimes, you might be in need of checking whether the specific JSON object has a specific key. The code snippet given below can be used for the purpose of doing this:

var ejson = {'key':'...xyz...', 'key2':'...pqr...'}; 
if(ejson.hasOwnProperty('key2'))
{ 
    //definition should be added here
}

You might also be in need of deleting an element from your JSON object. The “delete” keyword can be used for the purpose of selection of the element and then deleting it. Of course, the element will be selected from the specific JSON object. This is shown in the code given below:

var ejson = {'key':'...xyz...'}; 
delete ejson['key'];

At this point, you should be aware of how to perform the various operations on JSON data in Node.js.

Deja un comentario