JavaScript Tutorials

Putting Objects in Motion with JSON

The main reason JSON is so easy to use is because it’s already in a format that JavaScript can work with, so no conversion is necessary. For example, Listing 16-4 shows a JSON file containing information about this book.

Listing 16-4: JSON Data Describing Coding with JavaScript For Dummies

    <title>Displaying JSON Data</title>
      window.addEventListener('load', init, false);
      function init(e) {
          .addEventListener('click', documentLoader, false);
      function reqListener() {
        // convert the string from the file to an object with JSON.parse
        var obj = JSON.parse(this.responseText);
        // display the object's data like any object
        document.getElementById('book_title').innerHTML = obj.book_title;
        document.getElementById('book_author').innerHTML = obj.book_author;
        document.getElementById('summary').innerHTML = obj.summary;
      function documentLoader() {
        var oReq = new XMLHttpRequest();
        oReq.onload = reqListener;'get', 'listing16-4.json', true);
    <form id="myForm">
      <button id="myButton" type="button">Click to Load</button>
    <h1>Book Title</h1>
    <div id="book_title"></div>
    <div id="book_author"></div>
    <div id="summary"></div>

The key to displaying any JSON data that’s brought into a JavaScript Document from an external source is to convert it from a string to an object using the JSON.parse method. After you do that, you can access the values within the JSON file using dot notation or bracket notation as you would access the properties of any JavaScript object. Figure 16-10 shows the results of running Listing 16-5 in a web browser and pressing the button to load the JSON data.