JSON is becoming more and more the de facto standard data exchange format for AJAX applications. Many AJAX frameworks support JSON, many Web Services provide a JSON interface, and PHP 6 will most probably feature JSON support at the core of the language. Using JSON within JavaScript is quite simple, as well. The preceding code evaluates JSON and converts it into a JavaScript objecta simple eval() function call does the trick. The JSON notation from the previous sidebar, "Understanding JSON," is stored in a file called phrasebook.json; then, the following code reads in this file using XMLHttpRequest and then outputs some data from it: Using JSON for Data Deserialization (xmlhttpjson.html)
Warning Using eval() is general ly a bad idea, since you introduce a serious security vulnerability if the JSON comes from a nontrustworthy source. Due to the same-domain restriction of XMLHttpRequest, the JSON code can usually be trusted, but if you want to feel safer, download the JSON library json.js from http://www.json.org/js.html. Then, the following code replaces the eval() call: var book = json.parseJSON(); |