04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 17: Ajax and JSON<br />

This syntax represents a data object with four properties. Each property name must be enclosed in<br />

double quotes, and each value may be a string, a number, a Boolean, null , an object, or an array. The<br />

data - object format is also a valid object literal in JavaScript and can be assigned directly to a variable, as<br />

in this example:<br />

var person = {<br />

“name”: “Nicholas C. Zakas”,<br />

“title”: “Software Engineer”,<br />

“author”: true,<br />

“age”: 29<br />

};<br />

Note that although JavaScript doesn ’ t require object properties to be quoted, unquoted property names<br />

are considered a syntax error in JSON.<br />

Arrays are represented in JSON using the array - literal syntax from JavaScript. Here’s an example:<br />

[ 1, 2, “color”, true, null]<br />

Each value in an array may be a string, a number, a Boolean, null , an object, or an array. You can, for<br />

instance, create an array of objects describing people, as follows:<br />

[<br />

]<br />

{<br />

},<br />

{<br />

}<br />

“name”: “Nicholas C. Zakas”,<br />

“title”: “Software Engineer”,<br />

“author”: true,<br />

“age”: 29<br />

“name”: “Jim Smith”,<br />

“title”: “Salesperson”,<br />

“author”: false,<br />

“age”: 35<br />

582<br />

Keep in mind that this is plain text, not JavaScript code. The idea is to format data into a JSON structure<br />

on the server and pass it to the browser. Since JSON is a valid JavaScript representation for objects and<br />

arrays, a string of JSON data can be passed into the eval() function to return an object or array instance.<br />

For example, if the previous code were contained in a variable named jsonText , the following code<br />

would provide access to that data:<br />

//evaluate into an array<br />

var people = eval(jsonText);<br />

//access data<br />

alert(people[0].name);<br />

people[1].age = 36;<br />

if (people[0].author){<br />

alert(people[0].name + “ is an author”);<br />

}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!