String To JSON Object:
This is very much easier and straightforward as below:
As you can see, we are using the built-in global JSON Object to parse a string that has JSON Data. Also, it might be a 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:
Treat User-Defined Class Instance To JSON String:
However, you will need to be careful that you are declaring properties properly instead of declaring them as a 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, and I found a solution, which shows an 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:
Here, NodeJS automatically read the file, parses 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:
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:
Iterate Over A JSON Object:
Sometimes you will need to traverse through each element of the JSON object. This can be done in a for loop easily as like below:
However, the above code could give you an error in case the value itself is a JSON object. So, you will 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 has a specific key, we can check that with the below approach:
Pretty Print JSON Object:
The same applies if you are trying to write the JSON object in a file with a pretty printed format.
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.