CSE 154 LECTURE 13: XML AND JSON. Debugging responseXML in Firebug can examine the entire XML document, its node/tree structure.

Slides:



Advertisements
Similar presentations
Copyright © Steven W. Johnson
Advertisements

XML CS What is XML?  XML: a "skeleton" for creating markup languages  you already know it!  syntax is identical to XHTML's: content  languages.
Sue Wills July Objects The JavaScript language is completely centered around objects, and because of this, it is known as an Object Oriented Programming.
JavaScript and the DOM Les Carr COMP3001 Les Carr COMP3001.
1 Extensible Markup Language: XML HTML: portable, widely supported protocol for describing how to format data XML: portable, widely supported protocol.
CSE 190: Internet E-Commerce Lecture 17: XML, XSL.
1 Extensible Markup Language: XML HTML: widely supported protocol for formatting data XML: widely supported protocol for describing data XML is quickly.
CS 898N – Advanced World Wide Web Technologies Lecture 22: Applying XML Chin-Chih Chang
CSE 154 LECTURE 23: XML. Storing structured data in arbitrary text formats (bad) My note: BEGIN FROM: Alice Smith TO: Robert Jones.
The Document Object Model (DOM) & Asynchronous Javascript And XML (AJAX) : an introduction UFCEKG-20-2 : Data, Schemas and Applications.
CSE 154 LECTURE 24: XML AND JSON. Debugging responseXML in Firebug can examine the entire XML document, its node/tree structure.
Pemrograman Berbasis WEB XML part 2 -Aurelio Rahmadian- Sumber: w3cschools.com.
Javascript and the Web Whys and Hows of Javascript.
HTML DOM.  The HTML DOM defines a standard way for accessing and manipulating HTML documents.  The DOM presents an HTML document as a tree- structure.
JS: Document Object Model (DOM)
JavaScript & DOM Client-side scripting. JavaScript JavaScript is a tool to automate client side (which is implemented using HTML so far) JavaSript syntax.
D2L Notes Be sure to submit your link in the dropbox provided on D2L You can just upload an empty text file if a file upload is required Do not use D2L.
Lecture 13 – XML and JSON SFDV3011 – Advanced Web Development Reference: 1.
Review IDIA 619 Spring 2013 Bridget M. Blodgett. HTML A basic HTML document looks like this: Sample page Sample page This is a simple sample. HTML user.
Javascript. Outline Introduction Fundamental of JavaScript Javascript events management DOM and Dynamic HTML (DHTML)
JavaScript – The DOM JavaScript is object based The browser is object based – We can access the browser's objects in the same way we did JavaScript's Two.
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
5.2 DOM (Document Object Model). 2 Motto: To write it, it took three months; to conceive it three minutes; to collect the data in it — all my life. —F.
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
Javascript II DOM & JSON. In an effort to create increasingly interactive experiences on the web, programmers wanted access to the functionality of browsers.
JavaScript IV ECT 270 Robin Burke. Outline DOM JS document model review W3C DOM.
Chapter 2 Web Page Design Mr. Gironda. Elements of a Web Page These are things that most web pages use.
HTML Lesson 3 Hyper Text Markup Language. Assignment Part 2  Set the file name as “FirstName2.htm”  Set the title as “FirstName LastName First Web Site”
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
ECA 225 Applied Interactive Programming1 ECA 225 Applied Online Programming basics.
1 Dr Alexiei Dingli XML Technologies SAX and DOM.
Internet & World Wide Web How to Program, 5/e. © by Pearson Education, Inc. All Rights Reserved.2 Revised by Dr. T. Tran for CSI3140.
Markup basics. Markup languages add commentary to text files –so that the commentary can be ignored if not understood eg HyperText Markup Language –adds.
1 Javascript DOM Peter Atkinson. 2 Objectives Understand the nature and structure of the DOM Add and remove content from the page Access and change element.
HTML Basics. HTML Coding HTML Hypertext markup language The code used to create web pages.
AJAX. Ajax  $.get  $.post  $.getJSON  $.ajax  json and xml  Looping over data results, success and error callbacks.
Advanced DOM Builds on last presentation on DOM Allows you to dynamically create elements and position them on a page DOM methods/properties are W3C standard.
Tutorial 10 Programming with JavaScript. 2New Perspectives on HTML, XHTML, and XML, Comprehensive, 3rd Edition Objectives Learn the history of JavaScript.
Rich Internet Applications 2. Core JavaScript. The importance of JavaScript Many choices open to the developer for server-side Can choose server technology.
JavaScript. JavaScript Introduction JavaScript is the world's most popular programming language. It is the language for HTML and the web, for servers,
CHAPTER 8 AJAX & JSON WHAT IS AJAX? Ajax lets you…
JS: Document Object Model (DOM) DOM stands for Document Object Model, and allows programmers generic access to: DOM stands for Document Object Model, and.
Introduction to JavaScript MIS 3502, Spring 2016 Jeremy Shafer Department of MIS Fox School of Business Temple University 2/2/2016.
JQUERY AND AJAX
Javascript Basic Concepts Presentation By: Er. Sunny Chanday Lecturer CSE/IT RBIENT.
XML DOM Week 11 Web site:
JSON (Copied from and from Prof Da Silva) Week 12 Web site:
XML CS What is XML?  XML: a "skeleton" for creating markup languages  you already know it!  syntax is identical to XHTML's: content  languages.
Introduction to JavaScript MIS 3502, Fall 2016 Jeremy Shafer Department of MIS Fox School of Business Temple University 9/29/2016.
JavaScript Part 1 Introduction to scripting The ‘alert’ function.
Introduction to.
Build in Objects In JavaScript, almost "everything" is an object.
CSE 154 Lecture 12: XML.
Programming Web Pages with JavaScript
CIIT-Human Computer Interaction-CSC456-Fall-2015-Mr
CSE 154 Lecture 13: XML and JSON.
CSE 154 Lecture 12: XML.
Web Development & Design Foundations with HTML5
© 2015, Mike Murach & Associates, Inc.
CSE 154 Lecture 24: JSON.
Prepared for Md. Zakir Hossain Lecturer, CSE, DUET Prepared by Miton Chandra Datta
JavaScript Introduction
JavaScript an introduction.
DOM Document Object Model.
Web Systems Development (CSC-215)
CS 240 – Advanced Programming Concepts
Lecture 14: JSON and Web SERVICES
CSc 337 Lecture 13: JSON.
Introduction to AJAX and JSON
CSc 337 Lecture 13: JSON.
Presentation transcript:

CSE 154 LECTURE 13: XML AND JSON

Debugging responseXML in Firebug can examine the entire XML document, its node/tree structure

Schemas and Doctypes "rule books" describing which tags/attributes you want to allow in your data used to validate XML files to make sure they follow the rules of that "flavor" the W3C HTML validator uses an HTML schema to validate your HTML (related to tag) these are optional; if you don't have one, there are no rules beyond having well- formed XML syntax for more info: W3C XML Schema Document Type Definition (DTD) ("doctype") Document Type Definition (DTD)

Full list of XML DOM properties properties: nodeName, nodeType, nodeValue, attributes firstChild, lastChild, childNodes, nextSibling, previousSibling, parentNode methods: getElementById, getElementsByTagName, querySelector, querySelec torAll, getAttribute, hasAttribute, hasChildNodes appendChild, insertBefore, removeChild, replaceChild full reference

Exercise: Late day distribution Write a program that shows how many students turn homework in late for each assignment. Data service here: parameter: assignment=hw N

Pros and cons of XML pro: standard open format; don't have to "reinvent the wheel" for storing new types of data can represent almost any general kind of data (record, list, tree) easy to read (for humans and computers) lots of tools exist for working with XML in many languages con: bulky syntax/structure makes files large; can decrease performance (example)example can be hard to "shoehorn" data into a good XML format JavaScript code to navigate the XML DOM is bulky and generally not fun

An example of XML data Alice Smith Robert Jones Charles Dodd Tomorrow's "Birthday Bash" event! Hey guys, don't forget to call me this weekend! XML fairly simple to read and understand can be parsed by JavaScript code using XML DOM Is there any other data format that is more natural for JS code to process?

JavaScript Object Notation (JSON) JavaScript Object Notation (JSON): Data format that represents data as a set of JavaScript objects invented by JS guru Douglas Crockford of Yahoo!Douglas Crockford natively supported by all modern browsers (and libraries to support it in old ones) not yet as popular as XML, but steadily rising due to its simplicity and ease of use

Background: Creating a new object var name = { fieldName: value,... fieldName: value }; JS var pt = { x: 4, y: 3 }; pt.z = -1; alert("(" + pt.x + ", " + pt.y + ", " + pt.z + ")"); // (4, 3, -1) in JavaScript, you can create a new object without creating a class you can add properties to any object even after it is created ( z )

More about JavaScript object syntax var 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"]); // alert(person.friends[2])); // Zoidberg alert(person.getBeloved()); // Philip J. Fry loves Leela 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)

Repeated: Example XML data Alice Smith Robert Jones Charles Dodd Tomorrow's "Birthday Bash" event! Hey guys, don't forget to call me this weekend! XML Could we express this message data as a JavaScript object? Each attribute and tag could become a property or sub-object within the overall message object

The equivalant JSON data { "private": "true", "from": "Alice Smith "to": [ "Robert Jones "Charles Dodd ], "subject": "Tomorrow's \"Birthday Bash\" event!", "message": { "language": "english", "text": "Hey guys, don't forget to call me this weekend!" } } JSON

Valid JSON var student = { // no variable assignment "first_name": 'Bart', // strings must be double-quoted 'last_name': "Simpson", // property names must be quoted "birthdate": new Date("April 1, 1983"), // Date objects not supported "enroll": function() { // Functions not supported this.enrolled = true; } }; JSON 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 Unsupported types: Function, Date, RegExp, Error All others supported: Number, String, Boolean, Array, Object, null Numerous validators/formatters available: JSONLint, JSON Formatter & Validator, Free Formatter, JSON ValidatorJSONLintJSON Formatter & ValidatorFree FormatterJSON Validator

Browser JSON methodsJSON methods methoddescription JSON.parse( string )converts the given string of JSON data into an equivalent JavaScript object and returns it JSON.stringify( object )converts the given object into a string of JSON data (the opposite of JSON.parse) you can use Ajax to fetch data that is in JSON format then call JSON.parse on it to convert it into an object then interact with that object as you would with any other JavaScript object

JSON expressions exercise Given the JSON data at right, what expressions would produce: The window's title? (use the Console) The image's third coordinate? The number of messages? The y-offset of the last message? var data = JSON.parse(this.responseText); { "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" } JSON var title = data.window.title; var coord = data.image.coords[2]; var len = data.messages.length; var y = data.messages[len - 1].offset[1];

JSON example: Books Suppose we have a service books_json.php about library books. books_json.php If no query parameters are passed, it outputs a list of book categories: { "categories": ["computers", "cooking", "finance",...] } JSON Supply a category query parameter to see all books in one category: { "books": [ {"category": "cooking", "year": 2009, "price": 22.00, "title": "Breakfast for Dinner", "author": "Amanda Camp"}, {"category": "cooking", "year": 2010, "price": 75.00, "title": "21 Burgers for the 21st Century", "author": "Stuart Reges"},... ] } JSON

JSON exercise Write a page that processes this JSON book data. Initially the page lets the user choose a category, created from the JSON data. After choosing a category, the list of books in it appears: Books in category "Cooking":  Breakfast for Dinner, by Amanda Camp (2009)  21 Burgers for the 21st Century, by Stuart Reges (2010)  The Four Food Groups of Chocolate, by Victoria Kirst (2005)

Working with JSON book data function showBooks() { // add all books from the JSON data to the page's bulleted list var data = JSON.parse(this.responseText); for (var i = 0; i < data.books.length; i++) { var li = document.createElement("li"); li.innerHTML = data.books[i].title + ", by " + data.books[i].author + " (" + data.books[i].year + ")"; document.getElementById("books").appendChild(li); } } JS

Bad style: the eval function // var data = JSON.parse(this.responseText); var data = eval(this.responseText); // don't do this!... JS JavaScript includes an eval keyword that takes a string and runs it as code this is essentially the same as what JSON.parse does, but JSON.parse filters out potentially dangerous code; eval doesn't eval is evil and should not be used!