Tuesday, October 5, 2010

Data Communication in JSON

This week, I did some research on JSON, which I am going to use in my JavaScript Library for data representation. Here, I am going to talk about JSON in three aspects:

1. What is JSON?

JSON (JavaScript Object Notation) is a light weight data interchange format alternative to using XML. From its definition we can tell one important thing: JSON is a JavaScript Object. It is formed by numbers of key value pairs. Since the value can be any data type, developer can store other arrays or other objects, nesting them as deeply as needed.

An example of JSON would look like:
name : "Yichi",
major : "Computer Science",
hobbies : [
"Travel","Video Game"

An example of XML would look like:
<major>"Computer Science"</major>
<hobbies>"Video Game"</hobbies>

2. Why use JSON? (compare with XML)

As you might notice, JSON does not have tons of open and close tags or long list of attributes. It is more structured and more human readable than XML. Not only the size of data file is smaller, JSON is also easier to use in programing! Let's use the above data file as an example. Let's say I need to find the value of "name". If the data is in XML format, the code would look like:
var temp = xmldoc.getElementsByTagName('Name')[0].childNodes[0].nodeValue;
However, if the data is in JSON format, the code is much simpler:
var temp = jsondoc.name;

So, JSON is more JavaScript-Oriented than XML.

3. How to generate JSON?

Since WattDepot is going to provide data in XML format and I am not able to make any change on the server side, I need to find a way to convert XML data to JSON. Actually, there are some existing libraries out there for converting XML to JSON. One of them is Google Data API. In Google.Data.JSON package, it contains a xml_to_json($xml) method that can convert a XML file to JSON format. Here is a reference. In this case, I can simply use Google Data API in my library to handle the conversion.

Hopefully, my blog can help those JSON beginners like me:)

No comments:

Post a Comment