a blog for those who code

Thursday 3 September 2015

How to convert an object to JSON in Nodejs

In this post we are going to discuss about how to convert an object to JSON and JSON to object in NodeJS. It is the need of the time to serialize data, as we have numerous third party services to work with thus we want to give third parties safe access to raw data. JSON (a.k.a JavaScript Object Notation) is very closely related to JavaScript Objects because it is a subset of JavaScript.

At first we will create a module for us which will give us an object. Let's name the file as objects.js. The content of objects.js are as shown below.

module.exports = {
  nodeBook1 : {
    bookName: "Professional Node.js",
    author: "Pedro Teixeria",
    buy: "http://www.amazon.in/Professional-Node-JS-Building-Javascript-Based-Scalable/dp/8126539283/ref=as_sl_pc_tf_mfw?&linkCode=wey&tag=codidefi-21"
  nodeBook2 : {
    bookName: "Node.Js In Action",
    author: "Mike Cantelon, Marc Harter, T.J. Holowaychuk",
    buy: "http://www.amazon.in/Node-Js-In-Action-Mike-Cantelon/dp/9351192601/ref=as_sl_pc_tf_mfw?&linkCode=wey&tag=codidefi-21"
  nodeBook3 : {
    bookName: "Angular JS",
    author: "Brad Green",
    buy: "http://www.amazon.in/Angular-JS-Brad-Green/dp/9351101266/ref=as_sl_pc_tf_mfw?&linkCode=wey&tag=codidefi-21"
  nodeBook4 : {
    bookName: "Professional ASP NET MVC",
    author: "Jon Galloway",
    buy: "http://www.amazon.in/Professional-ASP-NET-MVC-Jon-Galloway/dp/1118794753/ref=as_sl_pc_tf_mfw?&linkCode=wey&tag=codidefi-21"

Our object contains the details of some book. If you are not familiar of creating modules then check Creating Own Custom Module in Nodejs. Now we are ready to create our main file where we are going to do the conversion. Let's name this files as convert.js. At first we need to get the object from objects.js file which can be done using require. We are going to use require to dynamically load our object at initialization. The full code to convert the object to JSON is shown below.

var objects = require('./objects');
var convertedObjects = JSON.stringify(objects);

The above code will give the output as shown below.

Now we are going to convert the JSON back to the object. For doing that we are going to use JSON.parse() as shown below.

var objects = require('./objects');
var convertedObjects = JSON.stringify(objects);

objects = JSON.parse(convertedObjects);

The above code will give us an output as shown below.

You can download the objects.js and convert.js files from GitHub. Please Like and Share CodingDefined.com Blog, if you find it interesting and helpful.

No comments:

Post a Comment