A 1 minute overview of JSON

JSON is (for the most part) perfectly legal JavaScript syntax, that has been around for quite a while. Think of it as shortcut literal syntax for quickly building a JavaScript object graph.

  • Every Object in JavaScript is an associative array (think Map in Java, a set of key -> value pairs).
  • In JavaScript, the curly braces {} are shorthand for “new Object()”
  • In JavaScript, the square brackets [] are shorthand for “new Array()”

So the following two snippets will build the exact same JS Object graph :

      // In JSON syntax 
      var contact = {
         'name': {
            'first': 'Lance',
            'last': 'Hankins'
         },
         'phone': {
            'mobile': '214.555.5555',
            'work': '972.555.5555'
         },
         'email':  {
            'work':'lhankins@work.com',
            'personal':'lhankins.hankins@home.com'
         }
      };

A non-JSON equivalent :

      // The more traditional NON-JSON way to do the same thing :
      var contact2 = new Object();

      contact2.name = new Object();
      contact2.name.first = 'Lance';
      contact2.name.last = 'Hankins';

      contact2.phone = new Object();
      contact2.phone.mobile = '214.555.5555';
      contact2.phone.work = '972.555.5555';

      contact2.email = new Object();
      contact2.email.work = 'lhankins@work.com';
      contact2.email.personal = 'lance.hankins@home.com';

Since JSON is so good at letting you concisely describe an object graph (hierarchical data), its often a great choice as the output format for server side responses to AJAX calls. On the client side, you can simply “eval” the response text to create the resultant JS object graph.

Here’s another link which also describes JSON in a concise form – and has a funny picture 🙂 Also, this post describes some of the exception cases where JSON is not actually legal JS (JS is a little more restrictive on the allowed characters for property names).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: