VYRE Company:Blog

An Introduction to JSON

01.03.2010 11:03 ( 0 comments )

by Gary Chisholm

 

I'm hoping to share my learning experience of JSON with the rest of you out there who, like me, have heard the word JSON (pronounced Jason) being thrown into conversation, documentation or elsewhere but have always been shy as to ask who this amazing JSON person is. In fact you've probably even seen JSON code, probably even understood it, but never put it into practice or had it explained to you.

What is JSON?

JSON stands for 'JavaScript Object Notation'. JSON is a versatile, lightweight way of defining objects within JavaScript and was defined by Doug Crockford of Yahoo in the early 90's - a very smart guy, I highly recommend looking at some of his video's over at YUI Theatre. Similar to XML, but apparently much more efficient because of its use of datatypes and speed, JSON provides hierarchical name-spacing for the definition of objects via way of a comma-separated mapping of 'key : value' pairs and is primarily used for the transportation of information as an object, again similar to XML. Before this gets too complicated, and it really shouldn't be, let me show you a simple JSON object that we'll use to define a person.

var person = {};

Okay, that's not quite JSON but it's the start of it. Just a variable, person, assigned to an empty object container, {}; the canvas of our fun. So let's add some data to define the person by mapping a key, name, to some value, the famous theoretical-physicist Erwin Schroedinger.

var person = {
 name : "Erwin Schroedinger" // person.name == "Erwin Schroedinger"
}

As you can see we now have our containing namespace of 'person' that contains a mapping of 'name' to 'Erwin Schroedinger''. In this example we have matched a string but because of the versatility of JavaScript we can map almost anything. In the below example you can see how I've expanded the 'person' object to contain multiple mappings between a key and values, arrays and even other JSON objects.

var person= {
 "name" : "Erwin Schroedinger", // person.name == "Erwin Schroedinger"
 "likes" : ["cats", "boxes"], // person.likes[1] == "boxes"
 "alive" : false, // Can use booleans, regex and ints as well
 "qualifications" : {
 "science" : "Distinction" // person.qualifications.science== "Distinction"
 }
};

 

person.qualifications.stenography = "Fail"; // Attaching a new value on the fly to the JSON object

Phew! No more code, I promise.

Why use JSON

Simply put it's completely up to you whether you think JSON is going to provide any benefit to your code in terms of readability, maintainability or efficiency. Like our first example where our 'person' only contained a single string, it may seem a little outrageous to go about the houses wrapping in an object, but the key thing to realise is that this one string now has a context; it belongs to something, it belongs to our 'person' which now has responsibility that we can later expand upon - like in the last line of the example where we added a new qualification for Erwin.

JSON is the start of object-oriented programming within JavaScript and generally provides the following core benefits:

  • Providing an abstract container that gives context to a group of variables or functions
  • A JavaScript alternative to XML for aggregating data
  • Improved code readability
  • First steps away from procedural programming towards object-oriented programming within JavaScript
  • Extensible; new items can be appended to the object on the fly
  • Improved debugging; Firebug and Chrome have DOM inspectors that allow you to view an object, and all values, as a whole
  • Use of jQuery's .serializeArray() to store all form fields as an array of objects mapping the field name to value; makes iterating over fields for validation very easy and dynamic.
  • Use of .supplant() to replace key names embedded in a string with values in a JSON string
  • Improved code control flow; data now represented as objects which have a state which will transition through the execution of the code
  • Using JSON for associative arrays. Retrieving or checking if an item exists within the object is as simple as calling a key within the object - unlike an array where you would, potentially, have to iterate over each and every value.

 

The fine print

To sum up, JSON is simply an alternative to XML. It is a lightweight way of representing a collection of information, whether it be data or functions, as an object whose main benefit is readability; which leads to easier to maintain, self-describing and well-structured code. The only downside is that JavaScript does have a list of reserved words that cannot be used as keys within an object so the way around this is to make sure that your keys are strings i.e. within quotes. 

Lastly, as keys map to values and values can be objects and, within Javascript, functions are objects you can map functions to keys. However, must JSON parsers will strip functions as they can be potentially harmful - similar to SQL injection - and should really only be used client side when JSON is used within internal scripts. For more reading on the matter check out the official JSON homepage or the following resources: JSON for the masses; The basics of object-oriented JavaScript; setting up a Flickr feed using JSON and Ajax using JSONP.

Comments