• No results found

Creating Objects with JSON

You might recall from Hour 6 that one convenient way to express an array is with square brackets:

Click he re to vie w code image

var categories = ["news", "sport", "films", "music", "comedy"];

JSON provides us with a somewhat similar shorthand for defining JavaScript objects.

Tip

Although it was developed for describing JavaScript objects, JSON is

independent of any language or platform. JSON libraries and tools exist for many programming languages, including Java, PHP, C, and others.

Properties

in curly braces, rather than square ones, and list object properties as "property":"value" pairs: var user = { "username" : "philb1234", "location" : "Spain", "height" : 1.80 } Tip

You may recall that using the statement

var myObject = new Object();

creates an “empty” instance of an object with no properties or methods. The equivalent in JSON notation, unsurprisingly, is

var myObject = {};

The object properties are immediately available to access in the usual fashion:

Click he re to vie w code image

var name = user.username; // variable 'name' contains 'philb1234'

Methods

You can add methods this way too, by using anonymous functions within the object definition:

Click he re to vie w code image

var user = { "username" : "philb1234", "location" : "Spain", "height" : 1.80, "setName":function(newName){ this.username=newName; } }

Then you can call the setName method in the usual way:

Click he re to vie w code image

var newname = prompt("Enter a new username:"); user.setName(newname);

Caution

While adding methods in this manner works fine in a JavaScript context, it is not permitted when using JSON as a general-purpose data interchange format.

Functions declared this way will not be parsed correctly in a browser using

native JSON parsing, though eval() will work. However, if you simply need to instantiate objects for use within your own script, you can add methods this way. See the following section on JSON security.

Arrays

Property values themselves can be JavaScript arrays:

Click he re to vie w code image

var bookListObject = {

"booklist": ["Foundation", "Dune",

"Eon",

"2001 A Space Odyssey",

"Stranger In A Strange Land"] }

In the preceding example, the object has a property named booklist, the value of which is an array. You can access the individual items in the array by passing the required array key (remember that the array keys begin at zero):

Click he re to vie w code image

var book = bookListObject.booklist[2]; // variable book has value "Eon"

The preceding line of code assigns to the variable book the second item in the

booklist array object, which is a property of the object named bookListObject.

Objects

The JSON object can even incorporate other objects. By making the array elements themselves JSON encoded objects, you can access them using dot notation.

In the following example code, the value associated with the property booklist is an array of JSON objects. Each JSON object has two "parameter":"value" pairs, holding the title and author respectively of the book in question.

After retrieving the array of books, as in the previous example, it is easy to then access the title and author properties:

Click he re to vie w code image

var bookListObject = {

"booklist": [{"title":"Foundation", "author":"Isaac Asimov"}, {"title":"Dune", "author":"Frank Herbert"},

{"title":"Eon", "author":"Greg Bear"},

{"title":"2001 A Space Odyssey", "author":"Arthur C. Clarke"}, {"title":"Stranger In A Strange Land", "author":"Robert A. Heinlein"}]

}

//show the author of the third book

alert(bookListObject.booklist[2].author); // displays "Greg Bear"

Try it Yourself: Manipulating JSON Objects

Let’s take the previous JSON object bookListObject and construct a user message that lists the books and authors in an easily read format. Create an

HTML file and enter the code from Listing 10.2. Your JSON object is identical to the one in the previous example, but this time you’re going to access the array of books, and step through it with a loop, building a message string by appending the books and authors as you go. Finally you’ll display the book information to the user.

LISTING 10.2 Handling JSON Multilevel Objects

Click he re to vie w code image

<!DOCTYPE html> <html> <head> <title>Understanding JSON</title> <script> var booklistObject = {

"booklist": [{"title":"Foundation", "author":"Isaac Asimov"}, {"title":"Dune", "author":"Frank Herbert"},

{"title":"Eon", "author":"Greg Bear"},

{"title":"2001 A Space Odyssey", "author":"Arthur C. Clarke"},

{"title":"Stranger In A Strange Land", "author":"Robert A. Heinlein"}]

}

// a variable to hold our user message var out = "";

// get the array

var books = booklistObject.booklist;

//Loop through array, getting the books one by one for(var i =0; i<books.length;i++) {

var booknumber = i+1;

out += "Book " + booknumber + " is: '" + books[i].title + "' by " + books[i].author + "\n"; } </script> </head> <body onload="alert(out)">

</body> </html>

After designing the JSON object, you declare a variable and assign an empty string. This variable will hold the output message as you build it:

var out = "";

Now you extract the array of books, assigning this array to a new variable, books, to avoid a lot of long-winded typing later:

Click he re to vie w code image

var books = booklistString.booklist;

Afterward, you simply need to loop through the books array, reading the title and author properties of each book object, and constructing a string to append to your output message:

Click he re to vie w code image

for(var i =0; i<books.length;i++) {

var booknumber = i+1; // array keys start at zero! out += "Book " + booknumber +

" is: '" + books[i].title + "' by " + books[i].author + "\n";

}

Finally, show your message to the user:

alert(out);

The result of running this script is shown in Figure 10.5.

FIGURE 10.5 Your book information is displayed to the user

Related documents