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.

Continue reading