23.04.2013 Views

javascript

javascript

javascript

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Parsing JSON<br />

CHAPTER 10 ■ SCRIPTING BOM<br />

More and more, XML is being supplanted by JSON, a data exchange format derived from JavaScript<br />

object and array literal syntax. JSON downloads snappy and is simple to parse. Just pass JSON data to<br />

window.eval(), and you have a JavaScript array or object. However, passing third-party JSON data, which<br />

may be malformed or malicious, to eval() is a horrible idea.<br />

■ Caution The eval() method is a powerful and dangerous tool. You should not pass any third-party data to it,<br />

because that third-party data could well contain malicious code for your users’ browsers to run. This could lead to<br />

all sorts of attacks and discomforts.<br />

For this reason, Internet Explorer 8, Firefox 3.5, and Safari 4 define a method, JSON.parse(), for you<br />

to use instead of eval(). For other versions and browsers, download the free JSON parser maintained by<br />

Douglas Crockford, JSON’s creator, from http://json.org/json2.js. Delete the first line:<br />

alert('IMPORTANT: Remove this line from json2.js before deployment.');<br />

Save the file as json2.js to the same directory as your other JavaScript files. Then link it in to your<br />

XHTML page. json2.js will define window.JSON only if it is missing. So for ten.html, we would link in<br />

json2.js like so:<br />

<br />

<br />

<br />

<br />

Getting StartED with JavaScript<br />

<br />

<br />

<br />

<br />

<br />

Running<br />

<br />

adidas<br />

ASICS<br />

Brooks<br />

New<br />

Balance<br />

Nike<br />

Saucony<br />

<br />

<br />

<br />

<br />

<br />

<br />

441

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

Saved successfully!

Ooh no, something went wrong!