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

<!--#include virtual="../s5/commontop.html" -->
      <title>Lecture 12: JSON &amp; Web Services — INFO 343 Autumn 2012</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>INFO 343 Lecture 12</h1>
            <h2>JSON &amp; Web Services</h2>
         </div>
      </div>

      <div class="presentation">
         <div class="slide">
            <h1>JSON &amp; Web Services</h1>
            <h3>Lecture 12</h3>
            <!-- <h4>Reading: 10.3–10.4</h4> -->

            <p class="license">
               Copyright 2010–12 Morgan Doocy and/or Marty Stepp, Jessica Miller.
            </p>

            <div class="w3c">
               <a href="http://validator.w3.org/check/referer"><img src="../s5/images/w3c-xhtml11.png" alt="Valid XHTML 1.1" /></a>
               <a href="http://jigsaw.w3.org/css-validator/check/referer"><img src="../s5/images/w3c-css.png" alt="Valid CSS!" /></a>
            </div>
         </div>
         
         
         
         <div class="slide titleslide">
            <h1>JSON</h1>

            <ol>
               <li>JSON</li>
               <li><strong>Using Web Services</strong></li>
            </ol>
         </div>
         
         
         
         <div class="slide">
            <h1>JavaScript Object Notation (JSON)</h1>
            
            <div style="text-align: center"><img src="json-business-card.jpg" alt="json" /></div>

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

            <p>
               <strong>JavaScript Object Notation (JSON):</strong><br/>
               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>“JSON has become the ‘X’ in ‘AJAX’.” (Douglas Crockford)</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>JSON example</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>
            <ul>
               <li>JSON is (mostly) just a JavaScript object (without the variable declaration)</li>
               <li>JSON’s media type is <code>application/json</code>; stored in a <samp>.json</samp> file</li>
            </ul>
         </div>

         
         
         <div class="slide">
            <h1>Valid JSON</h1>
<pre class="examplecode json">
<del>var student = </del>{                            <span class="comment">// no variable assignment</span>
   "first_name": <del>'</del>Bart<del>'</del>,                    <span class="comment">// strings must be double-quoted</span>
   <del>last_name</del>: "Simpson",                    <span class="comment">// property names must be quoted</span>
   "birthdate": <del>new Date("April 1, 1983")</del>,  <span class="comment">// Date objects not supported</span>
   "enroll": <del>function() {</del>                   <span class="comment">// Functions not supported</span>
      <del>this.enrolled = true;</del>
   <del>}</del>
}<del>;</del>
</pre>
            <ul>
               <li>
                  <p>JSON has a few rules that differ from regular JS:</p>
                  <ul>
                     <li>Strings must be double-quoted (in JS, single-quoted is also allowed)</li>
                     <li>Property names must be quoted (only required in JS if ambiguous)</li>
                     <li>Unsupported types: <code>Function</code>, <code>Date</code>, <code>RegExp</code>, <code>Error</code></li>
                     <li>All others supported: <code>Number</code>, <code>String</code>, <code>Boolean</code>, <code>Array</code>, <code>Object</code>, <code>null</code></li>
                  </ul>
               </li>
               <li>Numerous validators/formatters available: <a href="http://jsonlint.com">JSONLint</a>, <a href="http://jsonformatter.curiousconcept.com">JSON Formatter &amp; Validator</a>, <a href="http://www.freeformatter.com/json-validator.html">Free&nbsp;Formatter</a>, <a href="http://paulisageek.com/json_validator/">JSON Validator</a></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" style="width: 53%">
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>Fetching JSON data with Ajax</h1>
<pre class="examplecode json">
[
  {"fname": "Joseph",  "lname": "Adams",     "courses": [ "INFO 343", "CSE 154", ...]},
  {"fname": "Eric",    "lname": "Attersham", "courses": [ "ENGL 121", "ART 115", ...]},
  {"fname": "Fitzroy", "lname": "Bennet",    "courses": [ "CSE 331",  "CSE 372", ...]},
  ...,
]
</pre>
<pre class="examplecode js">
$.get('<em>students.json</em>', function(<em>students</em>) {
   for (var i = 0; i &lt; <em>students.length</em>; i++) {
      var $li = $('&lt;li&gt;').text(<em>students[i].lname</em> + ', ' + <em>students[i].fname</em>);
      $('ul#roster').append($li);
   });
});
</pre>
            <ul>
               <li>when fetching a JSON file, jQuery passes the <em>parsed</em> JavaScript object to our callback function</li>
               <li>(jQuery takes care of calling <code>JSON.parse()</code> for us)</li>
            </ul>
         </div>
         
         

         <div class="slide">
            <h1>Browser <a class="popup" href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/stringify">JSON methods</a> (which we won’t use)</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>
               <li style="font-weight: bold">BUT: jQuery’s Ajax functions parse JSON automatically, so we usually won’t need these</li>
            </ul>
         </div>





         <!-- <div class="slide">
            <h1>XML vs. JSON</h1>
            
            <h2>XML</h2>
            <ul>
               <li><strong>More semantically rich/flexible</strong> – sometimes the element/attribute distinction is important</li>
               <li><strong>More descriptive</strong> – all pieces of data are labeled with their kind</li>
               <li><strong>Less concise</strong> – each element requires an opening and closing tag</li>
            </ul>
            
            <h2>JSON</h2>
            <ul>
               <li><strong>Less semantically rich/flexible</strong> – cannot represent metadata as easily</li>
               <li><strong>Less descriptive</strong> – in the previous example, when migrating to JSON we lose the explicit indication that each object is a <code>book</code></li>
               <li><strong>More concise</strong> – a lot less bulky than XML</li>
            </ul>
         </div> -->
         


         <div class="slide titleslide">
            <h1>Web Services</h1>

            <ol>
               <li>JSON</li>
               <li><strong>Using Web Services</strong></li>
            </ol>
         </div>
         
         
         
         <div class="slide">
            <h1>Web data</h1>

            <ul>
               <li>most interesting web pages revolve around data
                  <ul>
                     <li>examples: Google, IMDB, Reddit, Facebook, YouTube, Flickr</li>
                     <li>can take many formats: text, HTML, XML, multimedia, JSON</li>
                  </ul>
               </li>
               <li>many of them allow us to access their data</li>
               <li>some even allow us to submit our own new data</li>
               <li>most server-side web programs accept <span class="term">parameters</span> that guide their execution</li>
            </ul>
         </div>



         <div class="slide">
            <h1>
               Query strings and parameters
               <span class="readingsection">(6.1.1)</span>
            </h1>

<pre class="syntaxtemplate url">
<var>URL</var><em>?</em><var>name</var><em>=</em><var>value</var><em>&amp;</em><var>name</var><em>=</em><var>value</var>...
</pre>

<pre class="url">
http://www.google.com/search?<em>q=Obama</em>
http://example.com/student_login.php?<em>username=sjm15</em>&amp;<em>id=1234567</em>
</pre>
            
            <ul>
               <li><span class="term">query string</span>: a set of parameters passed from a browser to a web server
                  <ul>
                     <li>often passed by placing name/value pairs at the end of a URL</li>
                     <li>above, parameter <code>username</code> has value <code>sjm15</code>, and <code>sid</code> has value <code>1234567</code></li>
                  </ul>
               </li>
               <li>a program on the server can examine and utilize the value of parameters</li>
               <li>the program can produce different output based on values passed by the user</li>
            </ul>
         </div>
         
         
         
         <div class="slide">
            <h1>Example: Exponent web service</h1>

            <ul>
               <li>
                  We have set up a web service that accepts a <code>base</code> and <code>exponent</code> and outputs <code>base</code> raised to the <code>exponent</code> power. For example, the following query should output <code>81</code>:

<pre class="examplecode url">
<a href="http://info343.ischool.uw.edu/exponent.php?base=3&amp;exponent=4">http://info343.ischool.uw.edu/exponent.php?<em>base=3</em>&amp;<em>exponent=4</em></a>
</pre>
               </li>
               <li>Try passing different parameters! (What happens if you don’t pass a parameter correctly?)</li>
         </div>




<!--#include virtual="../s5/commonbottom.html" -->