What is Node.js?
Node.js is an open source server environment, that uses JavaScript on the Server. It runs on multiple platforms (Windows, Linux, Unix, Mac OS X, etc.).
The main point of Node.js is that it uses asynchronous programming. Here is how Node.js handles a file request:
- Sends the task to the computer’s file system.
- Ready to handle the next request.
- When the file system has opened and read the file, the server returns the content to the client.
Therefore, Node.js eliminates the waiting, and simply continues with the next request. It is single-threaded, what makes Node.js very memory efficient.
Handling JSON files in Node.js
We are going to use the next JSON for the examples:
{
"uid": 41,
"user": "joki",
"password": "abcDEF123&",
"email": "joki@xyz.com"
}
And we save the file as jsonexample.json.
Next, we write a simple Node.js code to parse the JSON:
var fs = require("fs");
var file_content = fs.readFileSync('jsonexample.json');
var json = JSON.parse(file_content);
console.log(json.user);
Output: joki
We have used the singleton JSON.parse to convert the file contents to a JSON object.
In case we want to do the opposite, we can use JSON.stringify as it is shown here:
var json = { "name" : "Joaquin" };
var string = JSON.stringify(json);
As Node.js uses JavaScript in server, we could require the file directly as a JSON object.
var json = require('jsonexample.json');
console.log(json.user);
Modifying the JSON with Node.js
Adding or deleting an element to an existing JSON object very easy with Node.js
First, we have two ways to add a new element, using object or array format.
var json = {"name":"Joaquin"};
// 1. Object way
json.surname = "Ruiz";
// 2. Array way
json["surname"] = "Ruiz";
Also, if you want to remove an element from the JSON object, we can use the ‘delete‘ keyword.
var json = {"name":"Joaquin", "surname":"Ruiz"};
delete json['surname'];
Going through a JSON object with Node.js
In case we want to operate to every element of a JSON object, we can do it using a for loop as it is shown below:
var json = {"name":"Joaquin", "surname":"Ruiz"};
for(var key in json) {
console.log("> " + key + " = " + json[key]);
}
Output:
> name = Joaquin
> surname = Ruiz
Finally, in case we need to check if the JSON object has an element, we can use the method hasOwnProperty.
var json = {"name":"Joaquin", "surname":"Ruiz"};
if(json.hasOwnProperty('name')){
console.log(json.name);
}
else {
console.log("ERR");
}
In conclusion, I hope this post helps you to use JSON properly with Node.js, If you have any comments, please comment below. Happy coding!