info343/lectures/json-web-services/lecture23-json.shtml




<!DOCTYPE html>
<html>




   <head>
      <!-- metadata -->
      <meta charset="utf-8" />
      <meta name="author" content="Marty Stepp" />
      <meta name="description" content="Lecture slides to accompany Web Programming Step by Step, a college textbook on web programming." />
      <meta name="keywords" content="web programming, web design, html, html5, xhtml, css, css3, style sheets, layout, w3c, php, forms, javascript, dom, events, ajax, xml, json, sql, web security, cookie, session" />
      <meta name="HandheldFriendly" content="true" />
      <meta name="viewport" content="width=device-width, height=device-height, user-scalable=no" />      
      
      <!-- configuration parameters -->
      <!--
      <meta name="defaultView" content="slideshow" />
      <meta name="controlVis" content="hidden" />
      -->

      <!-- style sheet links -->
      <link rel="stylesheet" href="ui/default/slides.css" type="text/css" media="projection" id="slideProj" />
      <link rel="stylesheet" href="ui/default/outline.css" type="text/css" media="screen" id="outlineStyle" />
      <link rel="stylesheet" href="ui/default/print.css" type="text/css" media="print" id="slidePrint" />
      <link rel="stylesheet" href="ui/default/opera.css" type="text/css" media="projection" id="operaFix" />

      <!-- S5 JS -->
      <script src="http://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js" type="text/javascript"></script>
      <script src="http://ajax.googleapis.com/ajax/libs/scriptaculous/1.9.0/scriptaculous.js" type="text/javascript"></script>
      <script src="resources/slides.js" type="text/javascript"></script>
      <script src="ui/default/slides.js" type="text/javascript"></script>
      <!--
      <script src="resources/DrawingOverlay.js" type="text/javascript"></script>
      -->
      <title>Web Programming Step by Step, 2nd Edition Lecture 23: JSON</title>
   </head>

<body>
   <div class="layout">
      <div id="controls"><!-- DO NOT EDIT --></div>
      <div id="currentSlide"><!-- DO NOT EDIT --></div>
      <div id="header"></div>
      <div id="footer">
         <h1>Web Programming Step by Step, 2nd Edition</h1>
         <h2>Lab 23: JSON</h2>
      </div>
   </div>

   <div class="presentation">
      <div class="slide">
         <h1>Web Programming Step by Step, 2nd Edition</h1>
         <h2>Lecture 23: JSON</h2>
         <h4>Reading: 12.4</h4>

         <p class="license">
            Except where otherwise noted, the contents of this document are
            Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst.
            
            All rights reserved.
            Any redistribution, reproduction, transmission, or storage of part
            or all of the contents in any form is prohibited without the author's
            expressed written permission.
         </p>
         
         <div class="w3c">
            <a href="http://validator.w3.org/check/referer"><img src="images/w3c-html.png" alt="Valid HTML5" /></a>
            <a href="http://jigsaw.w3.org/css-validator/check/referer"><img src="images/w3c-css.png" alt="Valid CSS" /></a>
         </div>
      </div>


<div class="slide">
   <h1>Pros and cons of XML</h1>

   <ul>
      <li>pro:
         <ul>
            <li>standard open format; don't have to "reinvent the wheel" for storing new types of data</li>
            <li>can represent almost any general kind of data (record, list, tree)</li>
            <li>easy to read (for humans and computers)</li>
            <li>lots of tools exist for working with XML in many languages</li>
         </ul>
      </li>

      <li>
         con:
         <ul>
            <li>
               bulky syntax/structure makes files large; can decrease performance
               (<a href="http://en.wikipedia.org/wiki/MathML#Example_and_comparison_to_other_formats">example</a>)
            </li>
            <li>can be hard to "shoehorn" data into a good XML format</li>
            <li>JavaScript code to navigate the XML DOM is bulky and generally not fun</li>
         </ul>
      </li>
   </ul>
</div>



<div class="slide">
   <h1>JavaScript Object Notation (JSON)</h1>

   <div class="rightfigure">
      <img src="images/json-business-card.jpg" alt="json" />
   </div>

   <div class="rightfigure" style="clear: right;">
      <img src="images/douglas-crockford-chuck-norris.jpg" alt="json" />
   </div>

   <p>
      <strong>JavaScript Object Notation (JSON):</strong> Data format that represents data as a set of JavaScript objects
   </p>
   
   <ul>
      <li>invented by JS guru <a href="http://www.crockford.com/">Douglas Crockford</a> of Yahoo!</li>
      <li>natively supported by all modern browsers (and libraries to support it in old ones)</li>
      <li>not yet as popular as XML, but steadily rising due to its simplicity and ease of use</li>
   </ul>
</div>



<div class="slide">
   <h1>Recall: JavaScript object syntax</h1>
   
   <pre class="examplecode js">
var person = {
   name: "Philip J. Fry",                           <span class="comment">// string</span>
   age: 23,                                         <span class="comment">// number</span>
   "weight": 172.5,                                 <span class="comment">// number</span>
   friends: ["Farnsworth", "Hermes", "Zoidberg"],   <span class="comment">// array</span>
   getBeloved: function() { return this.name + " loves Leela"; }
};
alert(person.age);                                 <span class="comment">// 23</span>
alert(person["weight"]);                           <span class="comment">// 172.5</span>
alert(person.friends[2]));                         <span class="comment">// Zoidberg</span>
alert(person.getBeloved());                        <span class="comment">// Philip J. Fry loves Leela</span>
</pre>

   <ul>
      <li>in JavaScript, you can create a new object without creating a class</li>
      <li>the object can have methods (function properties) that refer to itself as <code>this</code></li>
      <li>can refer to the fields with <code>.<var>fieldName</var></code> or <code>["<var>fieldName</var>"]</code> syntax</li>
      <li>field names can optionally be put in quotes (e.g. <code>weight</code> above)</li>
   </ul>
</div>



<div class="slide">
   <h1>An example of XML data</h1>

   <pre class="examplecode xml">
<em>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</em>
<em>&lt;note private=&quot;true&quot;&gt;</em>
   <em>&lt;from&gt;</em>Alice Smith (alice@example.com)<em>&lt;/from&gt;</em>
   <em>&lt;to&gt;</em>Robert Jones (roberto@example.com)<em>&lt;/to&gt;</em>
   <em>&lt;to&gt;</em>Charles Dodd (cdodd@example.com)<em>&lt;/to&gt;</em>
   <em>&lt;subject&gt;</em>Tomorrow's "Birthday Bash" event!<em>&lt;/subject&gt;</em>
   <em>&lt;message language=&quot;english&quot;&gt;</em>
      Hey guys, don't forget to call me this weekend!
   <em>&lt;/message&gt;</em>
<em>&lt;/note&gt;</em>
</pre>
</div>



<div class="slide">
   <h1>The equivalant JSON data</h1>

   <pre class="examplecode json">
{
   "private": "true",
   "from": "Alice Smith (alice@example.com)",
   "to": [
      "Robert Jones (roberto@example.com)",
      "Charles Dodd (cdodd@example.com)"
   ],
   "subject": "Tomorrow's \"Birthday Bash\" event!",
   "message": {
      "language": "english",
      "text": "Hey guys, don't forget to call me this weekend!"
   }
}
</pre>
</div>



<div class="slide">
   <h1>Browser <a class="popup" href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/stringify">JSON methods</a></h1>

   <table class="standard">
      <tr>
         <th>method</th>
         <th>description</th>
      </tr>

      <tr>
         <td>
            <code>JSON.parse(<var>string</var>)</code>
         </td>
         <td>
            converts the given string of JSON data into an equivalent JavaScript object and returns it
         </td>
      </tr>

      <tr>
         <td>
            <code>JSON.stringify(<var>object</var>)</code>
         </td>
         <td>
            converts the given object into a string of JSON data (the opposite of <code>JSON.parse</code>)
         </td>
      </tr>
   </table>
   
   <ul>
      <li>you can use Ajax to fetch data that is in JSON format</li>
      <li>then call <code>JSON.parse</code> on it to convert it into an object</li>
      <li>then interact with that object as you would with any other JavaScript object</li>
   </ul>
</div>



<div class="slide">
   <h1>JSON expressions exercise</h1>

   <div class="rightfigure" style="text-align: left;">
      <pre class="examplecode js compressed">
var <em>data</em> = JSON.parse(ajax.responseText);
</pre>

      <pre class="examplecode json compressed">
{
   "window": {
      "title": "Sample Widget",
      "width": 500,
      "height": 500
   },
   "image": { 
      "src": "images/logo.png",
      "coords": [250, 150, 350, 400],
      "alignment": "center"
   },
   "messages": [
      {"text": "Save", "offset": [10, 30]}
      {"text": "Help", "offset": [ 0, 50]},
      {"text": "Quit", "offset": [30, 10]},
   ],
   "debug": "true"
}
</pre>
   </div>
   
   <p>
      Given the JSON data at right, what expressions would produce:
   </p>
   
   <ul>
      <li>The window's title?</li>
      <li>The image's third coordinate?</li>
      <li>The number of messages?</li>
      <li>The y-offset of the last message?</li>
   </ul>
   
   <pre class="incremental compressed">
var title = data.window.title;
var coord = data.image.coords[2];
var len = data.messages.length;
var y = data.messages[len - 1].offset[1];
</pre>
</div>



<div class="slide">
   <h1>JSON example: Books</h1>
   
   <p>
      Suppose we have a service <a href="http://webster.cs.washington.edu/books_json.php"><code>books_json.php</code></a> about library books.
   </p>
   
   <ul>
      <li>
         If no query parameters are passed, it outputs a list of book categories:
         
         <pre class="examplecode json">
{ &quot;categories&quot;: [&quot;computers&quot;, &quot;cooking&quot;, &quot;finance&quot;, ...] }
</pre>
      </li>

      <li>
         Supply a <code>category</code> query parameter to see all books in one category: <br />
         <a href="http://webster.cs.washington.edu/books_json.php?category=cooking">http://webster.cs.washington.edu/books_json.php?category=cooking</a>
         
         <pre class="examplecode json">
{
   &quot;books&quot;: [
      {&quot;category&quot;: &quot;cooking&quot;, &quot;year&quot;: 2009, &quot;price&quot;: 22.00, 
       &quot;title&quot;: &quot;Breakfast for Dinner&quot;, &quot;author&quot;: &quot;Amanda Camp&quot;},
      {&quot;category&quot;: &quot;cooking&quot;, &quot;year&quot;: 2010, &quot;price&quot;: 75.00, 
       &quot;title&quot;: &quot;21 Burgers for the 21st Century&quot;, &quot;author&quot;: &quot;Stuart Reges&quot;},
      ...
   ]
}
</pre>
      </li>
   </ul>
</div>



<div class="slide">
   <h1>JSON exercise</h1>

   <p>
      Write a page that processes this JSON book data.
   </p>
   
   <ul>
      <li>Initially the page lets the user choose a category, created from the JSON data.
         <ul>
            <li>
               <label><input type="radio" name="category" value="children" /> Children</label>
               <label><input type="radio" name="category" value="computers" /> Computers</label>
               <label><input type="radio" name="category" value="finance" /> Finance</label>
               <button>List Books</button>
            </li>
         </ul>
      </li>
      
      <li>
         After choosing a category, the list of books in it appears:
         
         <div style="border: 1px solid gray;">
            Books in category "Cooking":
               <ul>
               <li>Breakfast for Dinner, by Amanda Camp (2009)</li>
               <li>21 Burgers for the 21st Century, by Stuart Reges (2010)</li>
               <li>The Four Food Groups of Chocolate, by Victoria Kirst (2005)</li>
            </ul>
         </div>
      </li>
   </ul>
</div>



<div class="slide">
   <h1>Working with JSON book data</h1>

   <div class="example">
      <pre class="examplecode js">
function showBooks(ajax) {
   // add all books from the JSON data to the page's bulleted list
   var data = <em>JSON.parse(ajax.responseText)</em>;
   for (var i = 0; i &lt; data.books.length; i++) {
      var li = document.createElement(&quot;li&quot;);
      li.innerHTML = data.books[i].title + &quot;, by &quot; +
            data.books[i].author + &quot; (&quot; + data.books[i].year + &quot;)&quot;;
      $(&quot;books&quot;).appendChild(li);
   }
}
</pre>
   </div>
</div>



<div class="slide">
   <h1>Bad style: the <code>eval</code> function</h1>

   <pre class="examplecode js">
<span class="comment">// var data = JSON.parse(ajax.responseText);</span>
var data = <em>eval</em>(ajax.responseText);   <span class="comment">// don't do this!</span>
...
</pre>
   
   <ul>
      <li>JavaScript includes an <code>eval</code> keyword that takes a string and runs it as code</li>
      <li>this is essentially the same as what <code>JSON.parse</code> does,</li>
      <li>but <code>JSON.parse</code> filters out potentially dangerous code; <code>eval</code> doesn't</li>
      <li><code>eval</code> is evil and should not be used!</li>
   </ul>
</div>




      </div><!-- end div class="presentation" -->


      <!-- Google Analytics -->
      <script type="text/javascript">
         var _gaq = _gaq || [];
           _gaq.push(['_setAccount', 'UA-2729135-5']);
           _gaq.push(['_trackPageview']);
         
           (function() {
             //var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
             //ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
             //var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
           })();
      </script>
   </body>
</html>