Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Using JSON for Data (De)Serialization

var json = XMLHttp.responseText;
var book = eval("(" + json + ")");;

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 object—a 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)

<script language="JavaScript"
  type="text/javascript" src="xmlhttp.js"></script>
<script language="JavaScript"
  type="text/javascript">
var XMLHttp = getXMLHttp();
XMLHttp.open("GET", "phrasebook.json");
XMLHttp.onreadystatechange = handlerFunction;
XMLHttp.send(null);

function handlerFunction() {
  if (XMLHttp.readyState == 4) {
    var json = XMLHttp.responseText;
    var book = eval("(" + json + ")");
    var pubdate = book.pubdate;
    var title = book.title;
    var publisher = book.publisher;
    window.alert(title + " by " + publisher +
                 " (" + pubdate + ")");
  }
}
</script>
  • + Share This
  • 🔖 Save To Your Account