How To Work With JSON In Node.js / JavaScript

Standard

String To JSON Object:

This is very much easier and straight forward as below:

1
2
3
var jsonString = "{\"key\":\"value\"}";
var jsonObj = JSON.parse(jsonString);
console.log(jsonObj.key);

As you can see, we are using the built-in global JSON Object to parse a string which has JSON Data. Also, it might be good idea to use “.trim()” method on the string, if you think there might be some chance of extra space etc in the JSON string. Otherwise, it won’t get parsed and you will face an unexpected error.

JSON Object To String:

As like the previous case, we can use the same global object’s ‘stringify’ method to convert a given json to string data. This can be done easily as like below:

1
2
var jsonObj = {'key':'value'};
console.log(JSON.stringify(jsonObj));

Treat User Defined Class Instance To JSON String:

If you are writing JavaScript OOP style and want to convert an object instance to JSON like string(with its attributes name/value as key/value), You still can use the same JSON object to string approach as below:

1
2
3
4
5
6
7
8
9
function MyClass(){
this.a = 'some value';
this.b = {
  'key': 'another json structure'
};
}
var instance = new MyClass();
console.log(JSON.stringify(instance));

However, you will need to be careful that you are declaring properties properly instead of declaring them as local variable. This stack-overflow thread might also help in understanding the differences easily.

Read JSON From File System In NodeJS:

At first I tried googling about it, I found a solution, which shows example with file system support of nodejs(fs module). But, I don’t really see any meaning of that at all, as we can simply do the same thing by:

1
var jsonObj = require("./path/to/myjsonfile.json");

Here, NodeJS automatically read the file, parse the content to a JSON object and assigns that to the left hand side variable. It’s as simple as that!

Add New Element To Existing JSON Object:

Say, you have an existing json object, which you want to modify to add new key/value pair(s). You can do that using either of the two ways as below:

1
2
3
4
5
var myJson = {'key':'value'};
//new element
myJson.key2 = 'value2';
//or
myJson[key3] = 'value3';

Delete An Element From A JSON Object:

Well, to delete an element from a JSON object, it can be done by using the ‘delete’ keyword. An example is given below:

1
2
var myJson = {'key':'value'};
delete myJson['key'];

Iterate Over A JSON Object:

Sometimes you will might need to traverse through each elements of the JSON object. This can be done in a for loop easily as like below:

1
2
3
4
var myJson = {'key':'value', 'key2':'value2'};
for(var myKey in myJson) {
   console.log("key:"+myKey+", value:"+myJson[myKey]);
}

However, the above code could give you error in case the value itself is a JSON object. So, you will might want to check whether the value is itself json or not and handle it thereby.

Check Key Existence:

If at some point we need to check whether a json object have a specific key, we can check that with below approach:

1
2
3
4
var myJson = {'key':'value', 'key2':'value2'};
if(myJson.hasOwnProperty('key2')){
     //do something if the key exist
}

Comparing Two JSON Objects:

If you need to compare two JSON objects to check if they are equal or not, it’s better to iterate over and compare each property. As a reference, please visit this stack-overflow thread.