JSON - Fitter, Happier, More Productive

What is JSON?

JSON is Javascript Object Notation is a lightweight way to store and move data. If you are familiar with XML think of JSON as been ... fitter, happier, more productive.

So what is a Javascript object. Javascript objects consist of name : value pairs. They are defined within curly bracket as follows:


{"Author" : "Dickens"}

To list multiple name : values pairs separate them with commas as follows:

{
  "Title1": "The Adventures of Oliver Twist",
  "Title2": "The Life and Adventures of Nicholas Nickleby",
  "Title3": "The Old Curiosity Shop",
  "Title4": "A Christmas Carol",
  "Title5": "David Copperfield",
  "Title6": "Bleak House",
  "Title7": "A Tale of Two Cities",
  "Title8": "Great Expectations"
}

Hold on I thought you said JSON was fitter, happier, more productive. That looks repetitive and verbose. True and that is why we can also write JSON using arrays. Arrays are defined by square brackets.


{"name" : ["array value 1", "array value2"]}

So the above could also be represented as:

{ "title": [
"The Adventures of Oliver Twist", 
"The Life and Adventures of Nicholas Nickleby", 
"The Old Curiosity Shop",
"A Christmas Carol",
"David Copperfield",
"Bleak House",
"A Tale of Two Cities",
"Great Expectations"
] 
}

Tip: Notice how the above can be spread of multiple lines. JSON is stickler for the syntax of curly brackets, square brackets and commas but inside an array you can format this to be more readable with lines breaks.

We see this later but what you will commonly be doing with JSON is using data provided by a third party such as Facebook or Twitter.

jQuery and JSON

We are going to use jQuery to drab some data from JSON and add it to the HTML of a document. jQuery has a function called $.getJSON. This may look a little odd compared to other jQuery you have seen like show():

$(".more).show('slow');

Here the show() method is attached to an object in the HTML DOM, in this case objects of class "more". With $.getJSON it is not attached to a specific element in the DOM - it would be illogical to do so. Instead $.getJSON is a global function / method available whenever it is needed.

The $.getJSON method takes as its first argument the URL of the JSON file to load. As a second argument it takes a callback function - that is a function that will be called when the data is retrieved. Most commonly you would use an anonymous / inline function but named functions can be used as well. For an explanation of the difference between anonymous and named functions see the posted called "Anonymous / Inline vs Named Functions in Javascript".

Assuming we have a JSON file called 'dickens-books.json' in the same directory as the HTML file we wish to use the data in, then using an anonymous function, we would write:


$(document).ready(function() {
	 $.getJSON('dickens-books.json', function(data) {
     // to something
    });
});

We now have the data so lets do something with it. The data is a Javascript Object so we could use jQuery's each() method to loop around it.


<script language="JavaScript" type="text/javascript">
$(document).ready(function() {
	$.getJSON('dickens.json', function(data) {
	  var items = [];
	
	  $.each(data, function(key, val) {
		items.push('<li id="' + key + '">' + val + '</li>');
	  });
	
	  $("#myData").html(items.join("\n"));

	});
});
</script>

Here once the data is loaded we create an empty array called 'items'. We then use $.each() to populate that array with the keys and values from the JSON data.

For more examples of each() see the post "each() To Their Own - jQuery each() Explained".

For presentation the jQuery html() method takes the array as a string. The string is created using Javascript's join() method. You can read more about join() in the post "Manipulating Javascript Arrays with Split and Join.

Take a look at the demo.