CodingBison

Sometimes, we may need to transport an object between two hosts or may need to store the object so that we can access it later. For such tasks, JavaScript provides a text-based serialization method, known as JavaScript Object Notation (JSON). In fact, we can use JSON to not only convert JavaScript objects but also other JavaScript types like arrays, strings, numbers, booleans, and null values.

Even though JSON is used for JavaScript objects, it is language independent. Applications can use JSON to convert data into a format that can be transported over the network. And, since JSON provides a language-independent way to store and forward data, it can also serve as an alternative to XML. JSON was first specified by Douglas Crockford and its standard is available as RFC 4627.

We can use JSON.stringify() to serialize an object into a text-format. And, once we have data in a text-format provided by JSON, we can use JSON.parse() to parse the data back into a JavaScript type. Here is a simple example that serializes both an object and an array.

 <!doctype html>
 <html>
 <div id="idDiv"></div>

 <script type="text/javascript"> 
 // Get a handle of the div element.
 var elem = document.getElementById("idDiv");

 // Use JSON.stringify to serialize an object
 var obj = {name: "Smaug", author: "J. R. R. Tolkien", title: "The Hobbit"};
 json_text = JSON.stringify(obj);
 elem.innerHTML += "JSON text: " + json_text + "<br>"; 

 // Use JSON.parse to unserialize an object
 new_obj = JSON.parse(json_text);
 elem.innerHTML += "JSON parsed object: "; 
 for (var item in new_obj) {elem.innerHTML += new_obj[item] + ", ";}
 elem.innerHTML += "<br>Type of parsed obj: " + (typeof new_obj);

 // Use JSON.stringify to serialize an array (also an object!)
 var a = new Array("Kilgharrah", "Norbert", "Chrysophylax", "Vermithrax Pejorative");
 json_text = JSON.stringify(a);
 elem.innerHTML += "<br><br>JSON text: " + json_text + "<br>"; 

 // Use JSON.parse to unserialize the array 
 new_a = JSON.parse(json_text);
 elem.innerHTML += "JSON parsed object: ";
 for (var item in new_a) {elem.innerHTML += new_a[item] + ", ";}
 elem.innerHTML += "<br>Array.isArray(parsed array): " + Array.isArray(new_a);

 </script>
 </html>

We provide the output below. When we look at the output for a parsed array, we can see that Array.isArray() correctly identifies the parsed array.



Figure: Using JSON with objects.





comments powered by Disqus