JSON and JavaScript

We all know that XML is widely used in applications that leverage service-oriented architectures for sending and receiving data. But it cannot always be an ideal candidate to carry light-weight data. So JSON like format is increasingly becoming popular these days. JSON (JavaScript Object Notation) is a subset of the object literal notation of JavaScript. JSON is a text format that is completely language independent. When some data is JSON formatted, it is concise, human readable and easy to write.

Let’s see one JSON format data.

{
“Asia”:”China”,
“Africa”:”Zimbabwe”,
“North America”:”Canada”,
“South America”:”Brazil”,
“Antarctica”:”Netherlands”,
“Europe”:”Russia”,
“Australia”:”Sydney”,
“Cities”:[
“Shanghai”,
“Moscow”,
“Johannesburg”,
“Vancouver”,
“New York”,
“Kathmandu”,
“Singapore”
]
}

If the same data were to be represented in XML, then the structure would like as:

<?xml version=”1.0″ encoding=”utf-8″ ?>
<CountryCities>
<Asia>China</Asia>
<Africa>Zimbabwe</Africa>
<NorthAmerica>Canada</NorthAmerica>
<SouthAmerica>Brazil</SouthAmerica>
<Antarctica>Netherlands</Antarctica>
<Europe>Russia</Europe>
<Australia>Sydney</Australia>
<Cities>
<City>Shanghai</City>
<City>Moscow</City>
<City>Johannesburg</City>
<City>Vancouver</City>
<City>New York</City>
<City>Kathmandu</City>
<City>Singapore</City>
</Cities>
</CountryCities>

As compared to XML format, we see JSON is more concise, clear and has higher data-to-markup ratio. That’s why; JSON can be a better candidate for data interchange in client and server communication. However, we should not take JSON as a document format. Also, it is not a markup language. It is a subset of the object literal notation that JavaScript supports natively.

According to http://www.json.org/fatfree.html, the object notation in JSON can be done in two ways: Unordered key-value pairs and Ordered lists.

In the example above, the continent and country names are unordered key-value notation.
“Asia”:”China”,
“Africa”:”Zimbabwe”,
“North America”:”Canada”,
“South America”:”Brazil”,
“Antarctica”:”Netherlands”,
“Europe”:”Russia”,
“Australia”:”Sydney”,

And the city names are ordered list.
“Cities”:[“Shanghai”, “Moscow”, “Johannesburg”, “Vancouver”, “New York”, “Kathmandu”, “Singapore”]

The key is always represented in string type, while values may be any JSON types (string, number, Boolean, object, array and null).You may wonder why not date/time also. Because JavaScript also does not support date/time literal directly, instead JavaScript uses Date object. Se before representing any data in JSON format, one should also check for the compatible and supporting types. For .Net, we can see more about JSON types at http://msdn.microsoft.com/en-us/library/bb299886.aspx. There are plenty of open source tools and libraries that will help write and parse valid JSON text. Similarly, we can also validate the syntax check of JSON text using JSONLint. I think we may know about JSLint as well. It is a code quality tool and is used to validate JavaScript code.

Let’s come to an example of JSON and JavaScript. We will take the same JSON text in the example above to parse and convert into an object.

<%@Page Language=”C#” AutoEventWireup=”true” CodeBehind=”Default.aspx.cs” Inherits=”JsonAndJS._Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
<html xmlns=”http://www.w3.org/1999/xhtml&#8221; >
<head runat=”server”>
<title>Json and JavaScript</title>
<script language=”javascript” type=”text/javascript”>
var JsonString =
‘ {‘ +
‘ “Asia”: “China”,’ +
‘ “Africa”: “Zimbabwe”,’ +
‘ “NorthAmerica”: “Canada”,’ +
‘ “SouthAmerica”: “Brazil”,’ +
‘ “Antarctica”: “Netherlands”,’ +
‘ “Europe”: “Russia”,’ +
‘ “Australia”: “Sydney”,’ +
‘ “Cities”:  [‘ +
‘             “Shanghai”,’ +
‘             “Moscow”,’ +
‘             “Johannesburg”,’ +
‘             “Vancouver”,’ +
‘             “New York”,’ +
‘             “Kathmandu”,’ +
‘             “Singapore”‘ +
‘             ]’ +
‘}’;
function ListJsonValues() {
var CountryCities = eval(“(” + JsonString + “)”);
var CityNames = “<br />” + “City Names: ” + “<br />”;
for (var j = 0; j < CountryCities.Cities.length; j++) {
CityNames += “City: ” + (j + 1) + ” – ” + CountryCities.Cities[j] + “<br />”;
}
document.getElementById(‘dvPopularCities’).innerHTML = CityNames;
var CountryNames = “”;
CountryNames = “Countries: ” + “<br/>” + CountryCities.Asia + ” – ” + CountryCities.Africa + ” – ”
+ CountryCities.NorthAmerica + ” – ” + CountryCities.SouthAmerica + ” – ” + CountryCities.Antarctica + ” – ”
+ CountryCities.Europe + ” – ” + CountryCities.Australia + “<br />”;
document.getElementById(‘dvCountryList’).innerHTML = CountryNames;
}
</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<input id=”BtnList” type=”button” value=”List Country and City Names” onclick=”ListJsonValues();” />
</div>
<div id=”dvCountryList”>
</div>
<div id=”dvPopularCities”/>
<br />
</form>
</body>
</html>

One should try this example to see the result.
We see how the eval() method of JavaScript is used to parse the JSON text and return an object to CountryCities variable object. The extra parenthesis in eval() method is used to treat the JSON text as expression. But since eval() always parses the input text blindly, we have to be careful about the nature of input text expression from both coding and security point of views. There are various open source libraries in JavaScript which provide parse methods to return valid object out of JSON text.

Seeing the ease and nature of JSON text in AJAX world, JSON is gaining popularity rapidly. Even its MIME media type is now formalized as application/json. JSON may be favored among programmers to make point to point integration and data exchange between browser client and web server, but not similar to XML where it has huge support of integration in SOA world. But yes, if the data is small, JSON is a good option.

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: