CSE 154

Lecture 13: More Ajax and JSON

Today

Midterm Info

Homework announcements

  • Button font. The Shuffle button should be in the same font as the body. Unfortunately the current screen captures do not show this and they need to be fixed. However because our mistake we will not deduct for whether you style it (or not) in your final solution (but you should try to style it).
  • Copyright symbol: \u00A9 in text, © for html

Ajax Recap

Ajax Examples (Ajax tester and Ajax Duckystore)

Introduction to JSON

Got picture
  • Even more understanding of and confidence with HTML/CSS
  • Javasript: Events, Manipulating DOM objects, Intervals/Timers, Debugging strategies
  • Functional web pages!
Need picture

More practice with...

  • More practice with JavaScript mouse events, style changes, anonymous functions, using selectors, more elaborate manipulation of the DOM tree.
  • Help with section and lab examples
  • "More breathing room"
  • "How would you do this without Google handy?"

Recap: Ajax

A rewind back to Friday with some cleaned up slides

Ajax, Promises, and fetch

Summary: what's good about promises?

  • Helps deal with code that has an uncertain outcome
  • Separates completion from handling logic
    • Lets us reuse the same logic and handle completion in different ways (Ajax logic vs page insertion, for example)
  • Chaining of Promises gives us a nice data flow

JSON

JSON
JavaScript Object Notation

A data format that represents data as a set of JavaScript objects invented by JS guru Douglas Crockford of Yahoo! natively supported by all modern browsers (and libraries to support it in old ones)

But first... JavaScript objects


let myobj = {
  fieldName1: value1,
  ...
  fieldName: value
};

JS (example)

In JavaScript, you can create a new object without creating a "class" like you do in Java

You can add properties to any object even after it is created:

myobj.field87 = "wubba lubba";

JS (example)

Example


let person = {
    name: "Philip J. Fry",                           // string
    age: 23,                                         // number
    "weight": 172.5,                                 // number
    friends: ["Farnsworth", "Hermes", "Zoidberg"],   // array
    getBeloved: function() { return this.name + " loves Leela"; }
};
alert(person["age"]);                  // 23
alert(person.weight);                  // 172.5
alert(person.friends[2]));             // Zoidberg
alert(person.getBeloved());            // Philip J. Fry loves Leela

JS (example)

An object can have methods (function properties) that refer to itself as this
can refer to the fields with .fieldName or ["fieldName"] syntax
field names can optionally be put in quotes (e.g. weight above)

Examples of JS objects:

  • DOM elements
  • document, window
  • XMLHttpRequest
  • Promise

JavaScript Objects and JSON

JSON is a way of saving or storing javascript objects. (The technical term is "serializing" which is just a fancy word for turning an object into a savable string of characters)

Browser JSON methods:

What is JSON used for?

JSON data comes from many sources on the web:

  • web services use JSON to communicate
  • web servers store data as JSON files
  • databases sometimes use JSON to store, query, and return data

JSON is the de facto universal format for exchange of data

JSON Rules!

JSON has a few rules that differ from regular JS:

  • Strings must be quoted (in JS, single- or double-quoted are allowed)
  • All property/field names must be quoted
  • Values can be:
    • Number (23)
    • String ("string has to be quoted, like this")
    • Boolean (true, false)
    • Array ( [ "value1", 24, true, "hallo" ] )
    • Object ( { "nested" : "object", "which" : { "can" : "have more nested objects" } } )
    • null

Numerous validators/formatters available, eg JSONLint

JSON limitations

JSON can't handle certain data types, so these things just fall out of the object if you try to make JSON strings out of them:

  • Function
  • Date
  • RegExp
  • Error

To get Date objects or RegExp objects into your JSON, you could extract them as strings, and then rebuild them from strings.

However, since JSON is ideal for communicating across different types of systems, you can't put Javascript functions in JSON. Other languages wouldn't be able to read JSON effectively if it had Javascript code in it.

(This is also why Dates and RegExps can't go into the JSON object -- other languages wouldn't know how to interpret them for what they are.)

Valid JSON

{                          // no variable assignment
  "first_name": "Bart",    // strings and properties must be quoted
  "last_name": "Simpson",  // with double quotes
  "age" : 13,              // numbers can be here without quotes
  "cowabunga": true        // booleans can be here without quotes
}                          // no semicolon at the end

JSON

JSON exercise:

Given the JSON data at right, what expressions would produce. Assume the JSON data is stored in a string called json.

for instance, the window's title is data.window.title

  • What the debug flag is set to?
  • The image's third coordinate?
  • The number of messages?
  • The y-offset of the last message?
{
  "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, 20]},
      {"text": "Help", "offset": [ 0, 50]},
      {"text": "Quit", "offset": [30, 15]}
  ],
  "debug": "true"
}

Answers

let data = JSON.parse(json);
let title = data.debug;
let coord = data.image.coords[2];
let len = data.messages.length;
let y = data.messages[len - 1].offset[1];

JS