After the first post, JSON Quick start, you know what JSON is and how useful it’s in AJAX applications. This is more about JSON with more examples and advanced usages.

Using JSON

The JavaScript Object Notation (JSON) is a core feature of the language. It provides a concise mechanism for creating arrays and object graphs. In order to understand JSON, we need to know how JavaScript arrays work, so let’s cover the basics of them first.

JavaScript has a built-in Array class that can be instantiated using the new keyword:


myLibrary.books=new Array();

Arrays can have values assigned to them by number, much like a conventional C or Java array:


myLibrary.books[4]=somePredefinedBook;

Or they can be associated with a key value, like a Java Map or Python Dictionary, or, indeed, any JavaScript Object:

myLibrary.books["BestSeller"]=somePredefinedBook;

This syntax is good for fine-tuning, but building a large array or object in the first place can be tedious. The shorthand for creating a numerically indexed array is to use square braces, with the entries being written as a comma-separated list of values, thus:

myLibrary.books=[predefinedBook1,predefinedBook2,predefinedBook3];

And to build a JavaScript Object, we use curly braces, with each value written as a key:value pair:

myLibrary.books={

bestSeller : predefinedBook1,

cookbook : predefinedBook2,

spaceFiller : predefinedBook3

};

In both notations, extra white space is ignored, allowing us to pretty-print for clarity. Keys can also have spaces in them, and can be quoted in the JSON notation, for example:

“Best Seller” : predefinedBook1,

We can nest JSON notations to create one-line definitions of complex object hierarchies (albeit rather a long line):

var myLibrary={

location : "my house",

keywords : [ "root vegetables", "turnip", "tedium" ],

books: [

{

title : "Turnip Cultivation through the Ages",

authors : [

{ name: "Jim Brown", age: 9 },

{ name: "Dick Turnip", age: 312 }

],

publicationDate : "long ago"

},

{

title : "Turnip Cultivation through the Ages, vol. 2",

authors : [

{ name: "Jim Brown", age: 35 }

],

publicationDate : new Date(1605,11,05)

}

]

};

Sharp-eyed readers will have noted that we populated the publication date for the second book using a JavaScript Date object. In assigning the value we can use any JavaScript code, in fact, even a function that we defined ourselves:

function gunpowderPlot(){

return new Date(1605,11,05);

}

var volNum=2;

var turnipVol2={

title : "Turnip Cultivation through the Ages, vol. "+volNum,

authors : [

{ name: "Jim Brown", age: 35 }

],

publicationDate : gunpowderPlot()

}

We can also define member functions for our JSON-invoked objects, which can be invoked later by the object:

var turnipVol2={

title : "Turnip Cultivation through the Ages, vol. "+volNum,

authors : [

{ name: "Jim Brown", age: 35 }

],

publicationDate : gunpowderPlot()

},

summarize:function(len){

if (!len){ len=7; }

var summary=this.title+" by " + this.authors[0].name +" and his cronies is very boring. Z";

for (var i=0;i< len;i++){

summary+="z";

}

alert(summary);

}

};

...

turnipVol2.summarize(6);

The summarize() function has all the features of a standard JavaScript function, such as parameters and a context object identified by the keyword this. Indeed, once the object is created, it is just another JavaScript object, and we can mix and match the JavaScript and JSON notations as we please. We can use JavaScript to fine-tune an object declared in JSON:

var numbers={ one:1, two:2, three:3 };

numbers.five=5;

We initially define an object using JSON syntax and then add to it using plain JavaScript. Equally, we can extend our JavaScript-created objects using JSON:

var cookbook=new Object();

cookbook.pageCount=321;

cookbook.author={

firstName: "Harry",

secondName: "Christmas",

birthdate: new Date(1900,2,29),

interests: ["cheese","whistling","history of lighthouse keeping"]

};

With the built-in JavaScript Object and Array classes and the JSON notation, we can build object hierarchies as complicated as we like, and we could get by with nothing else. JavaScript also offers a means for creating objects that provides a comforting resemblance to class definitions for OO programmers, so let’s look at this next and see what it can offer us.