Recently, I started learning and working on the Node.js platform, so I am again brushing up on my long-forgotten JavaScript skills. JSON is a common format you encounter every now and then in JavaScript, whether it’s on the client side or server side. As NodeJs is a server-side platform, it has a little more capability than browser-based JavaScript, like writing to file systems, etc.
I am trying to aggregate most of the operations that we can usually perform related to a JSON object. Though most of this tutorial will apply to both kinds of JavaScript, few could be specific to Node.js.
String To JSON Object:
This is very much easier and straightforward as below:
var jsonString = "{\"key\":\"value\"}";
var jsonObj = JSON.parse(jsonString);
console.log(jsonObj.key);
Code language: JavaScript (javascript)
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 the “.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 in 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:
var jsonObj = {'key':'value'};
console.log(JSON.stringify(jsonObj));
Code language: JavaScript (javascript)
Treat User-Defined Class Instance To JSON String:
If you are writing JavaScript OOP style and want to convert an object instance to a JSON-like string(with its attributes name/value as key/value), You still can use the same JSON object-to-string approach as below:
function MyClass(){
this.a = 'some value';
this.b = {
'key': 'another json structure'
};
}
var instance = new MyClass();
console.log(JSON.stringify(instance));
Code language: JavaScript (javascript)
However, you must ensure that you declare properties properly instead of declaring them as a local variable. This stack-overflow thread might also help you understand 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:
var jsonObj = require("./path/to/myjsonfile.json");
Code language: JavaScript (javascript)
Here, NodeJS automatically reads 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 that you want to modify to add a new key/value pair(s). You can do that using either of the two ways below:
var myJson = {'key':'value'};
//new element
myJson.key2 = 'value2';
//or
myJson[key3] = 'value3';
Code language: JavaScript (javascript)
Delete An Element From A JSON Object:
Well, deleting an element from a JSON object can be done by using the ‘delete’ keyword. An example is given below:
var myJson = {'key':'value'};
delete myJson['key'];
Code language: JavaScript (javascript)
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:
var myJson = {'key':'value', 'key2':'value2'};
for(var myKey in myJson) {
console.log("key:"+myKey+", value:"+myJson[myKey]);
}
Code language: JavaScript (javascript)
However, the above code could give you an error if the value itself is a JSON object. So, you will want to check whether the value is itself JSON and handle it accordingly.
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:
var myJson = {'key':'value', 'key2':'value2'};
if(myJson.hasOwnProperty('key2')){
//do something if the key exist
}
Code language: JavaScript (javascript)
Pretty Print JSON Object:
In debugging, we always like to print data to the console to verify if it’s OK. If you are trying to see if a large JSON has something you are expecting, then it’s very hard to locate if it’s printed in a flat structure. In such cases, what you need is pretty much printing the JSON object. Here is the javascript code snippet that will do the trick:
JSON.stringify(myObj, null, 2);
Code language: JavaScript (javascript)
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.
Anything Else?
If you think anything is missing or something isn’t clear about using JSON data in node.js / JavaScript, please ask me to know by commenting here. Happy coding 🙂
Garcia says
Nice post, first time i see someone explain how to read json files with the require() function on node.
That is handy!
Thanks!
Also a nice addition would be how to prettify a JSON string, found an answer for that here: http://stackoverflow.com/questions/4810841/how-can-i-pretty-print-json-using-javascript
Nice tutorial
I am getting data from server
success:function(response)
{
alert(JSON.stringify(response));
}
Which is a string, and I want to change in it object to populate my html element
How I can do with parse?
var data = JSON.parse(body_your_response);
this will parse into a json object and you can pass it while rendering blade.
I’m new to Javascript and am struggling with something that should be quite simple. When I found your tutorial I was delighted. The first little bit is exactly what I want to do. However, I’m using nodejs rather than pure javascript. Perhaps that is problem.
Here are the results I’m getting with your first example:
var jsonString = “{‘key’:’value’}”;
undefined
> var jsonObj = JSON.parse(jsonString);
SyntaxError: Unexpected token ‘
at Object.parse (native)
at repl:1:20
at REPLServer.self.eval (repl.js:110:21)
at repl.js:249:20
at REPLServer.self.eval (repl.js:122:7)
at Interface. (repl.js:239:12)
at Interface.emit (events.js:95:17)
at Interface._onLine (readline.js:203:10)
at Interface._line (readline.js:532:8)
at Interface._ttyWrite (readline.js:761:14)
Running the json through jsonlint shows that it’s not valid unless it has double quotes, however, nodejs won’t accept doublequotes in my variable statement.
Can you tell me what is wrong and how I can get around it?
Hi Joy, glad to hear that you liked this tutorial. Also, thanks for your point. It was an error in my example, there will be double quote inside and need to be escaped(via \ char ). I have corrected it and now should work for you. Hope this helps.
how to check the repetition of a same key on a json file..
Consider I have a string formatted in such a way that I can easily parse it using JSON.parse() of JS. But the string contains repeating key, representing similar significance but with different values. And I want to handle both values of those keys… that I will, while parsing(if I could handle them separately), either store the values in list or store with different keys at my end. So I wanted to ask how I can get access to those values of repeating keys.
How to print json keys through node js program?
it’s hard to find simple explanations ! Many thanks !
Could you share the way to update value of an element node in Json Object?
Hi Rana,
if you can help me with this ? i want to read only the “output” “xReturnMsg” value in node.js application out of the following which is returned from a SQL Server Stored Proc.
{
“recordsets”: [],
“output”: {
“xReturnMsg”: “A04C4F2D-9D04-42AE-8690-F705827EE042”
},
“rowsAffected”: [],
“returnValue”: 0
}
can you please help me.