JavaScript Object Notation for Ajax Web services

Daniel Rubio digs into JavaScript Object Notation (JSON), the simplified data format that is gaining popularity with Ajax services and Web-based clients.

While Web services continue to be deployed on many corporate applications, a lot of thought continues to go into design issues ranging from reusability to security. Yet what is almost an afterthought is the actual payload structured as XML. After all, it's XML which provides Web services their platform/language independence, but as it turns out, there are certain Web service scenarios in which better payload alternatives can be used,...

one of them being JavaScript Object Notation (JSON), an approach which has recently grown in popularity for Web service clients in the form of a browser.

As its names implies, JSON is simply a data format, but one which is more naturally fit for browser data consumption. The reason for this is that JSON is a subset to JavaScript, the de facto programming language used in all browsers. By structuring a data payload as a JSON response, you are effectively bypassing the need to parse an XML document in a browser -- typically done via JavaScript of course -- to get to the actual data.

In this sense, JSON uses a stripped down syntax compliant with the native JavaScript interpreter provided on all browsers. Access and navigation to JSON data is done through the same standard JavaScript notation used to access string, array or hashtable values in a typical JavaScript application. Listing 1.1 illustrates what a JSON payload would look like.

Listing 1.1 : JSON payload example

{"item": {
          "description": {
              "title": "Backroad Mountain Bikes",
              "name": "Stump Jumper",
              "color": "chrome",
              "image": "/images/stumpjumper.jpg",
              "sizes": "17,18,19"
          },
          "cost": {
       "salestax": CA,
              "rate": 7,
              "base": 550,
              "custompaint": 150,
              "warranty": 50,
              "travelcase": 150
          },
          "instock": "yes"
      }}

Now compare this last JSON listing to its XML equivalent in Listing 1.2

Listing 1.2 XML payload example

<item>
    <description title="Backroad Mountain Bikes">
        <name>Stump Jumper</name>
        <color>chrome</color>
        <image>/images/stumpjumper.jpg
        <sizes>17,18,19</sizes>  
    </description>
    <cost salestax="CA" rate="7">
        <base>550</base> 
        <custompaint>150</custompaint> 
        <warranty>50</warranty> 
        <travelcase>150</travelcase>
    </cost>
    <instock>yes</instock>
</item>

At first sight JSON and XML are similar, but it's only when you get down to accessing the internal data structures that you realize JSON is easier to deal with in a browser setting. Tapping values in JSON is as simple as navigating a JavaScript object due to its syntax, but doing so for an XML response entails a lengthier process, one of parsing and navigating an ad-hoc tree structure not particularly natural to a browser environment.

Truth be told, JSON dates back to 2002, so its nothing out of the ordinary to structure data in a native JavaScript structure like an array or hashtable for later consumption by a browser. So why is it that JSON has recently gained popularity? The reason is another technology which has grown in recent times -- Ajax.

Prior to the emergence of Ajax, communication between a browser and its corresponding server application took place synchronously, or in other words, every request made by a browser required a complete screen refresh to obtain new data from the server. This of course minimized the need to parse data on the browser, with access to server side applications for customizing HTML markup on each request and the inevitable time lag experienced by a client browser there was rarely, if ever, a need to manipulate data on the browser directly, much less a need for XML or JSON.

With Ajax's first "A" standing for asynchronous and the "X" for XML, this pattern has changed considerably. Ajax has given way to the extremely common practice of transferring data between a browser and server application without the user awaiting a screen refresh -- or what is know as asynchronous communication -- and making such data exchange in XML fragments.

The biggest issue Ajax brings to the table is the increased demand for processing this data, which is obtained asynchronously. As noted earlier, parsing XML on the browser is not very straightforward, but by using an alternate syntax which is natively related to a browser's JavaScript engine, JSON is an ideal combination for services bound to clients in the form of a browser.

So may now be asking yourself, should I always use JSON instead of XML payloads? The short answer is, if your service client will be a browser then yes and if you will be using Ajax then it would be a definite yes. The question is actually reminiscent of other client/server technology design choices. Should you use XML when you knowingly have a Java/RMI client/server round-trip scenario? Or VB/.NET/DCOM over XML? Or CORBA instead of XML?

XML brings interoperability, but even the most noted XML pundits agree on XML's verbosity, which results in heavyweight transfers between client and server. This is why CORBA or Java/RMI will probably never be completely supplanted by XML payloads. Their data exchange process is optimized to work more effectively between client/server applications using such technologies. In this sense, JSON is the optimal payload solution for browser clients and Web services providers, given its close ties to JavaScript.

In terms of maturity, JSON's early beginnings have given it a series of stable implementations, which can be used in conjunction with the most common server-side technologies -- Java, .NET and PHP -- to more esoteric platforms like C, Delphi and Haskell -- all capable of generating JSON-compliant output. A complete list of language specific JSON utilities can be found at JSON homepage .

As far as real world usage is concerned, Yahoo! is one of the leading portal using JSON for Web services , but of course this is not counting the many smaller players, which are already taking advantage of JSON's less bulky syntax to provide an alternate Web service delivery format.

Though using JSON in favor of XML reduces the interoperability advantages inherent in XML, it enhances the overall performance and development effort required to consume services in a browser, not to mention those applications designed around Ajax. If you are on verge of developing Web services and your user base will consist of mostly browser-based clients, give JSON a closer look It provides compelling benefits to what is otherwise considered a default XML Web services response.

About the author

Daniel Rubio is an independent technology consultant specializing in enterprise and Web-based software, He blogs regularly on these and other software areas at Web Forefront.


This was first published in October 2006

Dig deeper on Ajax and RIA (Rich Internet Applications)

Pro+

Features

Enjoy the benefits of Pro+ membership, learn more and join.

0 comments

Oldest 

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

-ADS BY GOOGLE

SearchSoftwareQuality

SearchCloudApplications

SearchAWS

TheServerSide

SearchWinDevelopment

Close