search the site  

Enter search terms:


subscribe to newsletters   WebReference.com logo   WebReference.com
dev the Web
tip archive  •   about  •   contact  •   jobs  •   sitemap


[next]

An Introduction to JavaScript Object Notation (JSON)

By Rob Gravelle

Digg This Add to del.icio.us

ASP 3.0/.NET Developer
Jupitermedia
US-NY-New York

Justtechjobs.com Post A Job | Post A Resume

JavaScript Object Notation, or JSON for short, is a lightweight data-interchange format which may prove to be a viable alternative to XML for IT developers. The purpose of a data-interchange format is to transfer information between potentially incompatible technologies. For example, the sender may be a Java application running on Unix and the receiver could be a Visual Basic program running on Windows. In this instance one would require a standardized format to send the data because the applications could not communicate directly with each other. Even if they could, using a protocol such as TCP/IP or FTP, the data structures would have be to be defined somewhere. That's where the data-interchange format comes in. When XML came onto the scene in the late nineties, it was hailed as a godsend by many business managers because it was intuitive to look at and based on the well-known HTML language. Developers, on the other hand, were less impressed. It turns out that parsing XML was not nearly as simple as one might think! Today, despite the proliferation of programming libraries to perform many common tasks, from extracting node attributes to searching for specific data in the hierarchy, programmers are still faced with a learning curve when having to deal with the tags. Web developers faced a similar situation in the early days of dynamic HTML content. Eventually, frameworks such as Struts and Spring provided a way to handle "boiler plate" tag generation. Now, JSON offers developers a more familiar means of structuring data.

Change is in the Air

While XML was meant to transfer data between applications, its format was derived from Standard Generalized Markup Language (SGML), which bears a closer resemblance to HTML than to any programming language. One could say it's equally cumbersome in any language! JSON doesn't share this detriment since it's based on programming conventions found in the C family of languages, including C, C++, C#, Java, JavaScript, Perl, Python and others. It's also more succinct than tags-based XML. As we will soon see, the fact that it's a subset of JavaScript is advantageous with Web apps, where a lot of data exchange takes place. Moreover, JSON is especially well suited for AJAX calls.

Language Overview

JSON's raison d'être is to encapsulate an object in a meaningful and standardized way that can be easily understood by humans, as well as being rapidly parsed by machines. This is accomplished by structuring an object as literal representation using common programming syntax characters. Programmers have little difficulty in wrapping their heads around literals because they've been around for a long time. For instance, we almost instinctively know that the following code refers to an integer: "var intType = 3;" whereas this is a String: "var stringType = '3';" (technically a String within a String here!). Most languages can also represent more complex data types like arrays using literals such as: "var arrayLiteral = [1, '2', 3.34, 'dog'];" Notice that the array may contain several data types as well, depending on the language.

Let's get into some specifics regarding the JSON standard.

JSON objects are delimited by curly braces {}. Your initial thought might be that this would confuse the JavaScript interpreter because the curly braces are also used to enclose function bodies. In actuality, operator overloading is a long-standing practice and goes at least as far back to C++. Context is everything, and in each case, there are clues to help identify one from the other. JSON's signature is the key-value pairs used to represent the data, which are each separated by a colon (:):

Syntax String Example or Numeric Example
"key": value "name": "Fred" "price": 55.99

In the example above, the word "Fred" is enclosed by quotes to denote that it's a String data type, whereas a numeric value does not, as in any programming language. Keys and String values should always be enclosed by double quotes. In my last article, URPM's:AJAX Edition, I made the mistake of not enclosing the keys in quotes. It would seem I'm not alone. Jesse Skinner wrote about this very subject in his article entitled "JSON is not just Object Notation" (see references at the end of the article for a link to the site). It would seem that JSON is a lot pickier about format than JavaScript, as the latter will happily allow you to use single quotes or omit quotes around the keys, as I did. The moral of the story is this: while the JavaScript language provides some flexibility in the construction of Object literals, you may run into issues should you opt to use ready-made JSON parsers. I say may because I didn't encounter any problems when I tested some parsers on my class. Nonetheless, it costs nothing to use the stricter JSON standard.

JSON supports several data types including:

Here is a sample JSON object demonstrating various data types:

Note how few characters are used. Now that's compact!

Taking JSON for a Test Drive

So what can you do with it? Earlier, I mentioned that JSON is especially well suited for AJAX calls. The reason is that JavaScript understands the JSON syntax without requiring any parsing whatsoever! That's the advantage of using a programming-based format.

A common use for JSON is to pass objects between the Web page and a server-side application. In the following JSP example, a simple JSON object is constructed using the JSON Object utility class from the JSON.org home page.

The above code would send the following String to the browser. For illustration purposes, the sequence of the key-value pairs follows the same order in which they were added to the JSONObject. In practice, this wouldn't necessarily be the case, but is of no consequence; like hash tables, element ordering is a non-issue:

To access the object in JavaScript is even easier. All we need to do is use the built-in eval() function, as the String is already in syntactically correct JavaScript. Here's the client-side code:

We can now use the object like any other JavaScript class.

It can even be simpler than that! The JSONObject utility class has a constructor that accepts a Plain Old Java Object (POJO) class and a String Array. It uses class reflection to convert the public members in the Array to JSON properties. Here's how you would use the constructor:

Of course JSON works just as well going the other way. Again, there are plenty of utility scripts to choose from. As an example, here's one called JSON.js by Andrea Giammarchi. To use it, you simply call the encode function on your object like so:

Alternatively, you can create your own function by adding the JSON.encode() function to the Object prototype:

The encode's sister decode() function can then be used to parse the server response:


[next]

Recent Articles

WebReference.com site name
Perl Pragma Primer
Implement Drag and Drop in Your Web Apps: Part 2
How to Create an Ajax Autocomplete Text Field: Part 5
internet.com site name
SQL Server 2005 Express Edition - Part 22 - Upgrading from Microsoft SQL Server Desktop Engine (MSDE)
Vyatta: Downgrades that Pay Off
NetMotion Brings Cross-Network Support to Wireless VoIP

Access FREE HP High-Availability Solutions for Exchange 2007 Tools:
Whitepaper:
Backup and Recovery Best Practices for SQL Server 2005, Including HP Data Protector
Whitepaper:
Configuration Best Practices for Microsoft SQL Server 2005 with HP EVA4000 and HP Blade Servers
Whitepaper:
Best Practices for Microsoft Exchange 2007 with HP Server and Storage in Mid-range



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Win Server ‘08
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES