The Case For JSON: What Is It and Why Use It?

[[innerindex]]

A Little Background

After my post titled Look Ma, Cross Domain Scripting! a while back, I received a comment that was seeking more information. The commenter posts:

I’m looking at your code and it doesn’t explain exactly how this works, it just provides us with code to use. I’m curious as to what makes JSON work and what differences JSON has from XML. Is there any draw-backs or negative effects of using your solution? Is it a hack that will be fixed in the future?

If you know all about JSON and are wondering why to use it…I’ll tell you right now. Speed. But…if you are curious, I’ll attempt to answer the above questions, show some examples and then I’ll re-iterate Cross-Domain Scripting.

What is JSON?

JSON (or JavaScript Object Notation) is a highly portable data interchange format. While its structure is recognized natively by Javascript (as it is Javascript), its formatting conventions are easily recognized by other C-like languages. JSON.org has an excellent description:

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangable with programming languages also be based on these structures.

In JSON, they take on these forms:

  • An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).
  • An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).
  • A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
  • A string is a collection of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string.

Excepting a few encoding details, that completely describes the language.

JSON Structure

Here is a graphical representation of the formatting structure (image from JSON.org):


oav

Why JSON over XML?

Alright…I can already see the hordes of people wanting to wrench my head from my neck and drive lollipop sticks up my nose. But take a step back, put down the weapons and hear me out.

XML is versatile. You can create tags to your hearts content and endlessly nest data in seemingly sensible ways. XML is well known and most savvy developers can manipulate it in all sorts of ways. So what isn’t there to like about it? It just so happens that XML is like a fat tick after a good meal…bloated. Despite its ease of creation, the amount of busy tags makes it difficult to read with the human eye. Ok…don’t get me wrong, its easier to read than a Comma Separated file, but when compared to JSON, XML makes my head hurt.

JSON is simple and can represent the exact same data with fewer characters. How? Well, there are no tags. You give a member a name and then a value. Lets compare some examples…

JSON Examples

Lets say I want to expose two quotes from my friends at Uber-Geeks in some way…lets compare them in XML and JSON.

<quotes>
  <quote>"50 degrees all week today." - Ironmule</quote>
  <quote>"He wasn't naked...he had sneakers on." -Jon Emmons</quote>
</quotes>
{quotes:[
    "\"50 degrees all week today.\" - Ironmule",
    "\"He wasn't naked...he had sneakers on.\" -Jon Emmons"
  ]
}

That doesn’t seem too different…lets try something a little more complex. How about a Konfabulator Widget?

<widget>
    <debug>on</debug>
    <window title="Sample Konfabulator Widget">
        <name>main_window</name>
        <width>500</width>
        <height>500</height>
    </window>
    <image src="Images/Sun.png" name="sun1">
        <hoffset>250</hoffset>
        <voffset>250</voffset>
        <alignment>center</alignment>
    </image>
    <text data="Click Here" size="36" style="bold">
        <name>text1</name>
        <hoffset>250</hoffset>
        <voffset>100</voffset>
        <alignment>center</alignment>
        <onmouseup>
            sun1.opacity = (sun1.opacity / 100) * 90;
        </onmouseup>
    </text>
</widget>
{"widget": {
    "debug": "on",
    "window": {
        "title": "Sample Konfabulator Widget",
        "name": "main_window",
        "width": 500,
        "height": 500
    },
    "image": { 
        "src": "Images/Sun.png",
        "name": "sun1",
        "hOffset": 250,
        "vOffset": 250,
        "alignment": "center"
    },
    "text": {
        "data": "Click Here",
        "size": 36,
        "style": "bold",
        "name": "text1",
        "hOffset": 250,
        "vOffset": 100,
        "alignment": "center",
        "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
    }
}}  

The more complex the data you are trying to represent, the sexier JSON looks in comparison. Check here for some more examples…one is really long and looks quite sexy and readable in JSON and not so much in XML.

JSON and the Ajax Buzz

Ok, so if JSON and XML are pretty much peas in a pod when it comes to what they can represent, why make the switch (or at least…provide JSON). Ajax is our reason! You see, in an Ajax environment where we make calls to web services we expect to get some data back in some form. Well, if we receive XML back as a direct result of an Ajax call, we have to send that data through an XML parser before we can even begin to manipulate the data to be useful to JavaScript. If we receive the data in JSON…we don’t have to do anything but assign the results to a variable because JSON is already JavaScript. From there, we can manipulate the data as normal.

As Ajax methodologies (and even Cross Domain Scripting) become more commonplace, data format becomes vital to the efficiency of our applications. The Zimbra folks seem to have realized this and subsequently re-architected their entire application. Oh, and Script.aculo.us creator Thomas Fuchs seems to agree and states his opinion on XML in Ajax communication: Its dog slow…don’t do it.

JSON and Cross Domain Scripting

In my article Look Ma, Cross Domain Scripting, I discuss a method for doing Ajax-like calls to remote domains. As many of you may or may not know, XMLHttpRequest is restricted from making requests to remote domains.

The way it works is this: Somewhere out there exists a server side script that you wish to access in an Asynchronous fashion. Rather than attempting an XMLHttpRequest (which we know won’t work), all you do is dynamically create a <script> tag with its src set to the URL of the off-site page. When a script tag is inserted, browsers immediately execute the src! As long as the off-site page returns valid JSON, the JSON is executed locally.

For dynamically adding script tags, I use this library found over at Dan Theurer’s Blog. Its pretty simple and prevents duplicate script tags (which is a necessity).

Yahoo! sets a good example. They allow you to pass in two parameters to any of their web services (which return XML by default) and get the results in JSON.

Get JSON Output with output=json

By default the Yahoo! Web Services return output in XML format. To get output in JSON format, use the output=json parameter in the request:

http://api.search.yahoo.com/ ImageSearchService/V1/ imageSearch?appid=YahooDemo &query=Madonna&results=2 &output=json

Add a Callback with callback=function

The callback parameter (callback=function) wraps the JSON output text in parentheses and a function name of your choosing. For example:

http://api.search.yahoo.com/ ImageSearchService/V1/ imageSearch?appid=YahooDemo &query=Madonna&results=2 &output=json&callback=ws_results

This request results in this output:

ws_results( …json output… );

What is the drawback of this cross-domain solution? Well, I am relying on browsers to automatically execute the JavaScript in any dynamically created script tags. I have yet to find a mainstream browser that doesn’t…but the same goes for XMLHttpRequest. This method is used within Plymouth State University‘s live portal for Savable State Channels and we have yet to receive a support call regarding problems :)

JSON Resources

  • JSON.org: This site is the JSON site. It provides a description of what JSON is, provides some examples, and provides a list of JSON parsers for various languages.
  • Wikipedia: Enough said.
  • JSON Discussion Group
  • Yahoo’s JSON Web Services: Provides examples and suggestions on formatting your REST calls to return JSON as an option

Summary

XML works nicely. JSON works just as nicely and faster. This is why I’m a JSON fan. Speed is just as important as the data itself. Without speed…well, you’ve got crap.


Comments

17 responses to “The Case For JSON: What Is It and Why Use It?”

  1. I think what confuses me slightly is tag attributes and how they are handled. You have:

    #
    # main_window
    # 500
    # 500
    #

    And its corresponding:
    #”window”: {
    # “title”: “Sample Konfabulator Widget”,
    # “name”: “main_window”,
    # “width”: 500,
    # “height”: 500
    # },

    How does the notation know to add “title”: “Sample Konfabulator Widget” as the tag attribute and not a new element within the parent? What about multiple attributes? Proper XML should use child elements instead of multiple attributes, but I am sure you can come up with scenarios where it makes sense to use more than one attribute.

    Is there some other handling going on here?

  2. I think what is important is to think beyond what we know about XML to really see what is going on…for all intents and purposes, tag attributes and tags/content groups themselves are elements of the parent. JSON is merely meant as a data format and the parsers do the work of displaying the data appropriately. (Same goes for XML).

    In the Konfabulator example, all we really care about is that the “window” element has a “title” element with the content being “Sample Konfabulator Widget”. We could write the Konfabulator stuff in JSON notation, or in XML in these fashions:

    <window title=”Sample Konfabulator Widget”>

    </window>

    or

    <window>
      <title>Sample Konfabulator Widget</title>
      …
    </window>

    No matter which way you slice it, its the same data and will need to be parsed in some way.

    In regards to handling, JSON is handled all native-like by JavaScript (as I stated above), so I could receive the JSON version of the Konfabulator stuff and assign it to a variable like so:

    var konfab={“window”:{
    “title”: “Sample Konfabulator Widget”,
    “name”: “main_window”,
    “width”: 500,
    “height”: 500
    }};

    So now I’m able to do stuff like this:

    alert(konfab.window.title);

    konfab.window.width=10000000;

    document.write(‘<div id=”‘+konfab.window.name+’” style=”height: ‘+konfab.window.height+’px;width:’+kondfab.window.width+’px;”>’+konfab.window.title+'</div>’);

    With XML, I’d send it through a parser and end up with the same JavaScript object structure and would be able to manipulate it as normal…it’ll just take longer.

    Server-side its a different story…both XML and JSON need to be run through a parser of some sort…but as long as your data is formatted in some way, you’re golden!

  3. […] BorkWeb » The Case For JSON: What Is It and Why Use It? […]

  4. The topic anchors at the top of the post are really cool.

  5. […] Use JSON, not XML – Zimbra has almost fully converted all passing of XML to JSON […]

  6. When dealing with AJAX sites by all means avoid XML just for the sake of parsing speed. However when dealing in a enterprise SOA environment where interoptability between systems is the higher stake and most transformations arent done client-side, bulding the extra JSON interface is just an extra pain in the a$$. JSON is great because it can be parsed directly in Javascript, and it should only be used for this cause until it is able to describe datatypes.

  7. I have read the post thoroughly. But as I know, even in speed, JSON is slower than XML at all. There are many posts which said json is faster. While in my check, I used C# to test them. The jayrock parser 0.8s versus microsoft’s xml parser at about 0.4s. I write the xml in a complex way although. I mean
    the way like …. While in fact this can be simplified to . It is almost the same size or even smaller than JSON counter part. In the simplified case. The xml parser can finish the parse in 0.2s. XML is 2~4 times faster over JSON!
    Some one else also have tested this. See http://www.crossedconnections.org/w/index.php/2006/06/20/json-vs-xml-performance-update/ and http://dev.robertmao.com/2007/10/01/json-vs-xml-parsing-performance/.

    It seems no reason for JSON to survive. Even in javascript, we can use the msxml to parse xml. Msxml is much much faster than javascript json parser (either eval or else).

    I want to tell all that JSON is NOT fast at all.

    If

  8. Json is great but I dont think its faster than xml or anything. Well it all depends on the application. Using Ajax and XML is great specially with XSLT/XPATH/XQUERY. You can do just about anything on the client side by turning xml to pdf/html (just one example) if you were to do that with JSON might have to do a little bit more coding.

  9. […] In our case we are using JSON as response-type from an AJAX request. This is a sort of XML but a lot easier to read, especially when you work with a lot of data. For more information on JSON visit http://json.org/ or http://borkweb.com/story/the-case-for-json-what-is-it-and-why-use-it […]

  10. […] Matthew Batchelder gives the case to use JSON above XML. Obviously, JSON is more readable compared to XML. (Going through a large XML file is kind of a headache.) Using JSON avoids parsing XML since it is already recognized as a data structure. Thus avoiding the XML process would give the benefit of speed. […]

  11. Mailman Avatar
    Mailman

    I’m just learning JSON, and I’ve tried avoiding XML like the plague in general over the past 10 years developing in C, Php, ASP (JavaScript), ASP.NET (C#), ActionScript, and more. The MAIN reason is because the incredible bulkiness of XML tags in visual representation.

    Funny that I’m working in ColdFusion now though. LOL! Praise JSON. ;)

  12. A complete beginer to json. Json is quite compact than xml. But yet XML is far better than json. Json is only good with javascript.

  13. […] In our case we are using JSON as response-type from an AJAX request. This is a sort of XML but a lot easier to read, especially when you work with a lot of data. For more information on JSON visit http://json.org/ or http://borkweb.com/story/the-case-for-json-what-is-it-and-why-use-it […]

  14. average JOE Avatar
    average JOE

    for me, I don’t like json because it is one more thing to learn without much benefit/merit

  15. […] Wikipedia JSON.org The Case for JSON Share this […]

  16. Charlton Avatar
    Charlton

    totally new and have just begun to learn html/css/js/jquery a month ago. Need to use this with html5 local storage to build a web app prototype. Great explanation. JSON does look way sexier and much more modular in grouping similar properties.