8.1. What Is JSON?

JSON is a very lightweight data format based on a subset of the JavaScript syntax, namely array and object literals. Because it uses JavaScript syntax, JSON definitions can be included within JavaScript files and accessed without the extra parsing that comes with XML-based languages. But before you can use JSON, it's important to understand the specific JavaScript syntax for array and object literals.

8.1.1. Array Literals

Array literals are specified by using square brackets ( [ and ] ) to enclose a comma-delimited list of JavaScript values (meaning a string, number, Boolean, or null value), such as:

var aNames = ["Benjamin", "Michael", "Scott"];

This is functionally equivalent to the following, more traditional form:

var aNames = new Array("Benjamin", "Michael", "Scott");

Regardless of how the array is defined, the result is the same. Values are accessed in the array by using the array name and bracket notation:

alert(aNames[0]);   //outputs "Benjamin"
alert(aNames[1]);   //outputs "Michael"
alert(aNames[2]);   //outputs "Scott"

Note that the first position in the array is 0, and the value in that position is "Benjamin".

Because arrays in JavaScript are not typed, they can be used to store any number of different datatypes:

var aValues = ["string", 24, true, null];

This array contains a string, followed by a number, followed by a Boolean, followed by a null value. This is completely legal and perfectly fine JavaScript (though not recommended for maintainability ...

Get Professional Ajax, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.