JSON, or JavaScript Object Notation, is a data-interchange format that is becoming more widely accepted as a viable format for Ajax applications. It is essentially an associative array or a hash table, depending on the programming language with which you are most familiar. This means that names or labels are associated with values in an array structure or comma-delimited list. This format rivals XML as a data format used in Ajax applications because of its lightweight syntax and the adoption of JavaScript as a standard client-side scripting language. JSON parsing is also supported natively with JavaScript's eval method, which makes it extremely simple to parse when using it in your Ajax applications. The downfall is that the parsing can be quite slow due to the use of the eval method and, even more important, using this method can be very insecure. The bright side is that this does not mean that JSON is out of the running as an Ajax data-interchange format contender. It simply means that you need to be smarter when choosing it as your data format. This can be done by adding encrypted passwords to your requests for example, which we will cover in Chapter 23, "Securing Your Application."

Now that we have a little bit of background on JSON, let's take a look at the syntax in which to structure it.

The Syntax

The JSON syntax is very simple and arguably a bit sleeker than XML. XML can get quite heavy when there is a lot of data, which is due to the redundancy of elements, making JSON a great alternative. JSON is not a standard data-interchange format, but there are many parsers available that make it a viable option. There is just about every type of JSON parser available on http://www.json.org, and if you cannot find a parser for a language in which you are interested in using, you can easily write one because the syntax is not very difficult to parse.

The JSON syntax is very intuitive when you look at it from an object-oriented angle. The structure of a JSON file is representative of a JavaScript object in the way that one file can consist of multiple objects, arrays, strings, numbers, and Booleans. Table 3.1 displays a list of data types formatted as JSON.

Table 3.1. JSON Representations of Each Data Type

Data Types

JSON Representations


"icon": "img/mail.gif"


"mynumber": 100


"myboolean": true


"items": [  {    "action": "alert('Grace Hopper');",    "icon": "img/mail.gif",    "item": ["Grace Hopper", "<b>BUG Found</b>",   "2006-03-31 09:27:26"]   },   {     "action": "alert('Pi Sheng');",     "icon": "img/mail.gif",     "item": ["Pi Sheng", "Movable type", "2006- 01-15 12:32:45"]  } ]


"categories": {     "category": ["From", "Subject", "Date"] }

All JSON data types are represented by a name or label as a string value followed by a colon. The values are what differ from one type to another. The simple types are self-explanatorya string value is represented as a string, a number is represented as a number, and a Boolean is represented as a value of TRue or false. The more complicated data types are arrays and objects. An array is represented as a comma-delimited list, which is contained within square brackets. A JSON object contains properties of any data type, within curly braces, such as a class would be formatted in other languages; the difference here is that we do not give a name to the main structure.

Using JSON

After you understand the syntax of JSON, formatting it is fairly simple. Comparing JSON with an XML format is interesting when working with large amounts of data because the JSON format ultimately becomes a much smaller data structure. In this section, we will convert the samples from the XML section and compare the two different formats to see the differences in terms of size and readability. After we draw the comparisons, we will cover parsing the JSON data structures in the next section. I have converted the XML file from the last section into a JSON data structure in Listing 3.8.

Listing 3.8. The Completed JSON Sample Format (email.js)

{     "data":     {         "categories":         {             "category": ["From", "Subject", "Date"]         },         "row":         {            "items":             [                     {                     "action": "alert('Grace Hopper');",                     "icon": "img/mail.gif",                     "item": ["Grace Hopper", "<b>BUG Found</b>", "2006-03-31 09:27:26"]                 },                 {                     "action": "alert('Pi Sheng');",                     "icon": "img/mail.gif",                     "item": ["Pi Sheng", "Movable type", "2006-01-15 12:32:45"]                 }             ]         }     } }

As you can see, it is much slimmer than the XML version because of the lack of redundancy in tag names, which is the nature of the XML structure. Keep in mind that this file can be a lot more compactI have simply chosen to display it in a way that is more readable. The JSON data structure is approximately 200 characters smaller with a total character count of 316, whereas the XML data format has 519 characters, which is quite a difference. As the data in your application grows, it can cause a bandwidth issue, but as I mentioned earlier, the client-side parsing can be slower with JSON. What it ultimately comes down to is what format is more usable in your application, or what is easier to parse and write for you.

Parsing JSON

Parsing JSON as a response from an XHR differs from parsing all other data-interchange formats that can be used with Ajax. Unlike using the responseXML property, which is used for XML, we need to use the responseText property. Using this property with plain text or straight XHTML is trivial because we would use solely it as the value of the response, as in the following example:


Using this property with JSON is also trivial; it is just different based on the fact that we need to evaluate the responseText in order for it to be readable for parsing. By evaluating the response, we are essentially creating a JavaScript object from the data, which can then be used on the client side as the display data in the GUI. In order to parse the data, we will begin by creating the callback method, checking the ready state of the request, and evaluating the responseText (see Listing 3.9).

Listing 3.9. Creating a Response Object (ajax.js)

function onJSONResponse() {     if(checkReadyState(request, 'loading') == true)     {         eval("var response = ("+request.responseText+")");     } }

As we covered in the XML section of this chapter, the checkReadyState method is used for two different purposeschecking that the response has been completely loaded, and displaying a loading message to the user in any HTML element that is specified as the parameter. After the response has been completely loaded, we will begin parsing by evaluating the responseText from the XHR and creating an object named response as a result. This object can then be used to target any values that were added to the object during the evaluation or data parsing. Let's start by targeting the categories from the data and appending them to the body div that is in our index HTML file (see Listing 3.10).

Listing 3.10. Parsing JSON Categories (ajax.js)

[View full width]

// Categories document.getElementById("body").innerHTML = "------------<br/>"; document.getElementById("body").innerHTML += "<b>Categories</b><br/>"; document.getElementById("body").innerHTML += "------------<br/>"; for(var i in response.data.categories.category) {     document.getElementById("body").innerHTML += response.data.categories.category[i]  +"<br/>"; }

As you can see, it is very easy to target the data after it is parsed into a JavaScript object. Property values are accessible by simply using dot syntax to target them by the proper path. In Listing 3.10, we are targeting the categories, which are arrays based on the fact that there were multiple values in the category property. In order to target this category array, we use the dot syntax to literally write the path to that specific property in the response object.

Now that we have the categories parsed and displayed in the body div, we will target the items. In order to target the items, we will need to nest two for loops as we did in the XML example, but parsing the actual values will be slightly different for the actual items and their attributes. See Listing 3.11 to get an idea of how we parse this data.

Listing 3.11. Parsing JSON Items (ajax.js)

// Items document.getElementById("body").innerHTML += "------------<br/>"; document.getElementById("body").innerHTML += "<b>Items</b><br/>"; document.getElementById("body").innerHTML += "------------<br/>"; for(var i in response.data.row.items) {     for(var j in response.data.row.items[i])     {         document.getElementById("body").innerHTML += response.data.row.items[i][j] +"<br/>";     }     document.getElementById("body").innerHTML += "------------<br/>"; }

As I mentioned, the item attributes are targeted much differently than they were with the XML parsing. We can simply do a for...in loop to target all the property values within a specific object. In this case, we are using this method of data retrieval to access the values of the item attributes and the item arrays.

Using JSON as a response format can be even more powerful by specifying event handlers within the data format to represent specific object types that can be rendered to the document. We will not go into this level of detail, but it is important knowledge to be aware of because it might be very beneficial to your future applications. I will leave you with an example of how to approach structuring this data:

"items": [     {"value": "Read e-mail", "onclick": "displayEmailDetail()"} ]

Now that we have a detailed understanding of how to handle an Ajax response, we can focus on formatting it and creating GUI with CSS or XHTML.

Ajax for Web Application Developers
Ajax for Web Application Developers
ISBN: 0672329123
EAN: 2147483647
Year: 2007
Pages: 129
Authors: Kris Hadlock

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net