JSON 101
Introduction
JSON (JavaScript Object Notation) is a lightweight data-interchange format that’s easy for humans to read and write; and easy for machines to parse and generate. In actuality, JSON is a text format that’s completely language independent but uses conventions familiar to programmers within the C-family of languages. JSON can be used like XML to transfer information from one language to another, for instance PHP to Javascript. However, in this tutorial I will show how JSON can be used within Javascript to quickly create clean code.
Usage
Lets start with arrays. In JSON an array begins with a [ (left bracket) and ends with a ] (right bracket). Values are separated by a , (comma).
Unidimensional:
// Normal Javascript:
var myArray = new Array();
myArray[0] = "Element One";
myArray[1] = "Element Two";
myArray[2] = "Element Three";
myArray[3] = "Element Four";
...
or
var myArray = new Array("Element One","Element Two","Element Three", ...);
// With JSON:
var myArray = ["Element One","Element Two","Element Three", ...];
Multidimensional:
// Normal Javascript: var myArray = new Array(); myArray[0] = new Array(); myArray[0][0] = "Array One, Element One"; myArray[0][1] = "Array One, Element Two"; ... myArray[1] = new Array(); myArray[1][0] = "Array Two, Element One"; myArray[1][1] = "Array Two, Element Two"; ... // With JSON: var myArray = [ ["Array One, Element One","Array One, Element Two", ...], ["Array Two, Element One","Array Two, Element Two", ...], ... ];
As you can see JSON provides a somewhat short-hand approach to writing code, thereby reducing the amount of typing. Now lets move onto objects. In JSON an object begins with a { (left brace) and ends with a } (right brace). Each name is followed by a : (colon) and the name/value pairs are separated by a , (comma).
For example:
// Normal Javascript:
var myObj = function(){
this.x = 1;
this.y = 2;
this.z = 3;
};
alert(myObj.x);
// With JSON:
var myObj = {
x: 1,
y: 2,
z: 3
};
alert(myObj.x);
This can be used in conjunction with the prototype object to create a class structure. For example:
var myClass = function(){ this.init.apply(this,arguments) };
myClass.prototype = {
init: function(y){
this.x = 10;
this.y = y;
},
calc: function(){
with(this){
return x*y;
}
}
};
var newClass = new myClass(5);
alert(newClass.calc());
But that’s for another tutorial. If you wish to learn more, goto www.json.org.
Here are some additional links if anyone’s interested:
Mastering JSON
JSON Wikipedia Entry
couchdb: couchdb 101 | breaker of stuff, destroyer of things said,
December 11, 2008 at 8:58 am
[...] Just in case you don’t understand json: webt.wordpress.com/2007/10/01/json/ [...]