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

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.

XML:
  1. <quotes>
  2.   <quote>"50 degrees all week today." - Ironmule</quote>
  3.   <quote>"He wasn't naked...he had sneakers on." -Jon Emmons</quote>
  4. </quotes>

JavaScript:
  1. {quotes:[
  2.     "\"50 degrees all week today.\" - Ironmule",
  3.     "\"He wasn't naked...he had sneakers on.\" -Jon Emmons"
  4.   ]
  5. }

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

XML:
  1. <widget>
  2.     <debug>on</debug>
  3.     <window title="Sample Konfabulator Widget">
  4.         <name>main_window</name>
  5.         <width>500</width>
  6.         <height>500</height>
  7.     </window>
  8.     <image src="Images/Sun.png" name="sun1">
  9.         <hoffset>250</hoffset>
  10.         <voffset>250</voffset>
  11.         <alignment>center</alignment>
  12.     </image>
  13.     <text data="Click Here" size="36" style="bold">
  14.         <name>text1</name>
  15.         <hoffset>250</hoffset>
  16.         <voffset>100</voffset>
  17.         <alignment>center</alignment>
  18.         <onmouseup>
  19.             sun1.opacity = (sun1.opacity / 100) * 90;
  20.         </onmouseup>
  21.     </text>
  22. </widget>

JavaScript:
  1. {"widget": {
  2.     "debug": "on",
  3.     "window": {
  4.         "title": "Sample Konfabulator Widget",
  5.         "name": "main_window",
  6.         "width": 500,
  7.         "height": 500
  8.     },
  9.     "image": {
  10.         "src": "Images/Sun.png",
  11.         "name": "sun1",
  12.         "hOffset": 250,
  13.         "vOffset": 250,
  14.         "alignment": "center"
  15.     },
  16.     "text": {
  17.         "data": "Click Here",
  18.         "size": 36,
  19.         "style": "bold",
  20.         "name": "text1",
  21.         "hOffset": 250,
  22.         "vOffset": 100,
  23.         "alignment": "center",
  24.         "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
  25.     }
  26. }}

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.

Discuss This Article


8 Responses to “The Case For JSON: What Is It and Why Use It?”

  1. AvatarWandering Pig Effer

    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?

    Reply to this comment.
    1
  2. AvatarMatt
    Author Comment

    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!

    Reply to this comment.
    2
  3. pingback pingback:
    Adminspotting.net » The Case For JSON: What Is It and Why Use It?

    [...] Full article here. [...]

    Reply to this comment.
    3
  4. pingback pingback:
    alexking.org: Blog > Around the web

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

    Reply to this comment.
    4
  5. AvatarPJ

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

    Reply to this comment.
    5
  6. pingback pingback:
    BorkWeb » The Ajax Experience: Leveraging Ajax for Enterprise Application Development

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

    Reply to this comment.
    6
  7. Avataredgecrush3r

    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.

    Reply to this comment.
    7
  8. AvatarBian

    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

    Reply to this comment.
    8

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Comment Preview:

 (5180) - json (88) - what is JSON (86) - json examples (84) - json example (82) - json structure (46) - Why JSON (42) - json length (28) - JSON hash (26) - example json (20) - json cross domain (16) - json dictionary (12) - json what is (11) - sample json (11) - json associative array (10) - cross (9) - iterate json (7) - why json? (7) - json samples (7) - What is JSON? (7) - json datetime (6) - json sample (6) - json iterate (6) - cross domain scripting json (6) - json C# (5) - json sort (5) - sort JSON (5) - json hashtable (5) - json array (4) - javascript sort json (4) - iterate json object (4) - json iterating (4) - json speed (4) - json ajax example (4) - how json works (4) - hashtable JSON (3) - json collections (3) - call json example (3) - jquery json parser (3) - javascript iterate json object (3) - why use json (3) - prototype iterate json (3) - length of JSON Arrays (3) - json array iterate (3) - parsing json jquery (3) - json iterate javascript (3) - c# json (3) - json backslash (3) - iterate json data (3) - JSON parsing speed (3) - is JSON faster? (3) - json format example (3) - iterating JSON (3) - example using json (2) - json escape data (2) - parsing speed json xml (2) - JSON Plugin example (2) - return dict json (2) - prototype json hash (2) - c# convert time from json string to datetime (2) - json example complex (2) - sort json object (2) - jquery sort json (2) - c# hashtable json (2) - json vs xml speed (2) - javascript iterate through json object (2) - parse speed json xml (2) - json vs xml speed jquery (2) - json javascript iterating (2) - complete json examples (2) - C# json to hashtable (2) - Example with JSON (2) - JSon get length (2) - javascript json to hash (2) - json simple example (2) - json for length (2) - jquery xml parsing speed (2) - json parser tutorial (2) - json quotes in content (2) - javascript output image from json (2) - json use (2) - JSON reply (2) - nested json arrays (2) - json-c example (2) - iterate a json object (2) - prototype json nested (2) - json nested array (2) - how does json work (2) - c# json example (2) - c# webservice xmlhttp cross domain (2) - array to json (2) - json tutorial example (2) - json struct (2) - Sort JSON Array (2) - arrays in JSON (2) - JSON associative (2) - C# parse javascript array (2) - passing variables to json webservice (2) - XML performance JSON (2) - iterating json hash object (2) - json sample extjs (2) - JSON array length (2) - json array C# (2) - json image example (2) - json to hash (2) - JSON image (2) - json image collection (2) - json escape (2) - json and hash (2) - javascript iterate json array (2) - iterate through JSON object (2) - JSON C example (2) - json get (2) - iterate json javascript (2) - json 2 (2) - json javascript compare attribute name (2) - cross domain JSON (2) - nested array json (2) - convert c# to JSON (1) - iterate through name-value pairs json (1) - web services json c# (1) - parsing speed xml javascript json (1) - javascript how to parse json datetime (1) - nested json in java (1) - jquery convert array to json (1) - C# Json samples (1) - json array json sample (1) - yahoo quotes json (1) - json:array sort (1) - javascript json sort() (1) - READ DIV TAGS AND WRITE IN XML FORMAT C# (1) - json associative object (1) - JSON sample scripts (1) - AJAX Webservice json parameter (1) - sorting json object (1) - json nesting array (1) - json array escape quotes (1) - json hash lookup (1) - json datetime C# (1) - passing JavaScript array from webservice in C# (1) - json hashtable c# .net (1) - C# json lists (1) - Iterating JSON String (1) - JQuery sort numbers separated by comma (1) - xml to json prototype (1) - json array hash example (1) - JSON what is it? (1) - example.json (1) - json to c# (1) - json create structure (1) -