Categories
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

<html>
  <head>
    <title>Displaying JSON Data</title>
    <script>
      window.addEventListener('load', init, false);
      function init(e) {
        document
          .getElementById('myButton')
          .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;
        oReq.open('get', 'listing16-4.json', true);
        oReq.send();
      }
    </script>
  </head>
  <body>
    <form id="myForm">
      <button id="myButton" type="button">Click to Load</button>
    </form>
    <h1>Book Title</h1>
    <div id="book_title"></div>
    <h2>Authors</h2>
    <div id="book_author"></div>
    <h2>Summary</h2>
    <div id="summary"></div>
  </body>
</html>

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.