json – ajax - rest javascript object notation

23
JSON – AJAX - REST JavaScript Object Notation http://www.json.org/

Upload: william-stokes

Post on 16-Dec-2015

251 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: JSON – AJAX - REST JavaScript Object Notation

JSON – AJAX - REST

JavaScript Object Notationhttp://www.json.org/

Page 2: JSON – AJAX - REST JavaScript Object Notation

JSON

• JSON: JavaScript Object Notation

• JSON is syntax for storing and exchanging text information. Much like XML.

• JSON is smaller than XML, and faster and easier to parse.

Page 3: JSON – AJAX - REST JavaScript Object Notation

Json Object

{”persons": [{ "firstName":”Mary" , ”surName":”Pop" }, { "firstName":”Peter" , ”surName":”Pan" }, { "firstName":”Erkki" , ”surName":”Aalto" }]}object

JSON uses JavaScript syntax for describing data objects, but JSON is still language and platform independent. JSON parsers and JSON libraries exists for many different programming languages.

The persons object is an array of 3 personnel records (objects)

Page 4: JSON – AJAX - REST JavaScript Object Notation

innerHTML<html><body><p>Manufacturer: <span id="jmanufacturer"></span><br />Operating system: <span id="jos"></span><br />Released: <span id="jreleased"></span><br />Type: <span id="jtype"></span><br />Apps: <span id="japps"></span><br /></p>

<script>var JSONObject = {"manufacturer":"Jolla Ltd","os":"Sailfish","released":"21.11.2012","type":"multitasking","apps":"Android"};document.getElementById("jmanufacturer").innerHTML=JSONObject.manufacturer;document.getElementById("jos").innerHTML=JSONObject.os;document.getElementById("jreleased").innerHTML=JSONObject.released;document.getElementById("jtype").innerHTML=JSONObject.type;document.getElementById("japps").innerHTML=JSONObject.apps;</script></body></html>

JS: Each HTML element has an innerHTML property that defines both the HTML code and the text that occurs between that element's opening and closing tag.

Page 5: JSON – AJAX - REST JavaScript Object Notation

XML <-> JSON<?xml version="1.0" encoding="ISO-8859-1"?><reqistry> <usage>Employees</usage> <expert>

<person><firstname>Mary</firstname><surname>Programmer</surname>

</person><expertise>

<field>Web</field><skillname>html</skillname><years>12</years>

</expertise> </expert> <expert>

<person><firstname>Ted</firstname><surname>Technology</surname>

</person><expertise>

<field>Electronics</field><skillname>Embedded

systems</skillname><years>12</years>

</expertise> </expert></reqistry>

h tt p : / / j s o n t o x m l . u ti l i ti e s - o n l i n e . i n f o /R E M : E X T R A S P A C E S M I G H T A P P E A R ! !

{ "reqistry":{ "usage": "Employees", "expert":[ { "person":{ "firstname": "Mary", "surname": "Programmer" }, "expertise":{ "field": "Web", "skillname": "html", "years": "12" } }, { "person":{ "firstname": "Ted", "surname": "Technology" }, "expertise":{ "field": "Electronics", "skillname": "Embedded systems", "years": "12" } } ] }}

Page 6: JSON – AJAX - REST JavaScript Object Notation

JSON Syntax

Syntax for passing around objects that contain name/value pairs, arrays and other objects

{ "bookstore":{ "book":{ "title": "Learning XML", "author": "Sam R. Samsonite", "year": "2003", "price": "39.95" } }}

JSON validatorhttp://www.freeformatter.com/json-validator.html

<?xml version="1.0" encoding="ISO-8859-1"?><bookstore> <book>

<title>Learning XML</title><author>Sam R. Samsonite</author><year>2003</year><price>39.95</price>

</book></bookstore>

• Squiggly (curly) brackets act as 'containers'• Square brackets holds arrays see expert in previous slide

• Names and values are separated by a colon.• Array elements are separated by commas

Page 7: JSON – AJAX - REST JavaScript Object Notation

Like / Unlike XMLLike XML

JSON is plain text JSON is "self-describing" (human readable) JSON is hierarchical (values within values) JSON can be parsed by JavaScript JSON data can be transported using AJAX

Unlike XML

No end tag Shorter Quicker to read and write Can be parsed using built-in JavaScript eval() Uses arrays No reserved words

Page 8: JSON – AJAX - REST JavaScript Object Notation

Json Object is written inside curly bracketsvar jsonObject = { "anObject": { "numericProperty": -122, "stringProperty": "An offensive \" is problematic", "nullProperty": null, "booleanProperty": true, "dateProperty": "2011-09-23" }, " arrayOfObjects": [ { " firstname": " Kake ", " lastname " : " Box " }, { "firstname": " Kake2 ", " lastname " : " Box2 " } ], "arrayOfIntegers": [ 1, 2, 3, 4, 5 ]}

JSON syntax is a subset of the JavaScript object notation syntax.Data is in name/value pairsData is separated by commaCurly brackets holds objectsSquare brackets holds arrays

JSON values can be:A number (integer or floating point)A string (in double quotes)A Boolean (true or false)An array (in square brackets)An object (in curly brackets)null

In the example , the object “arrayOfObjects" is an array containing objects. Each object is a record of a person (with a first name and a last name).

Page 9: JSON – AJAX - REST JavaScript Object Notation

JSON Object creation<h2>JSON Object Creation in JavaScript</h2><p>Title: <span id="jtitle"></span><br />Author: <span id="jauthor"></span><br />Year: <span id="jyear"></span><br />Price: <span id="jprice"></span><br /></p><script>//create json object on the flyvar jsonObject= {"bookstore":{ "book":{ "title": "Learning XML", "author": "Sam R. Samsonite", "year": "2003", "price": "39.95" } }};document.getElementById("jtitle").innerHTML=jsonObject.bookstore.book.title;document.getElementById("jauthor").innerHTML=jsonObject.bookstore.book.author;document.getElementById("jyear").innerHTML=jsonObject.bookstore.book.year;document.getElementById("jprice").innerHTML=jsonObject.bookstore.book.price</script>

Page 10: JSON – AJAX - REST JavaScript Object Notation

Array of ObjectsTitle: <span id="jtitle1"></span><br />..Title: <span id="jtitle2"></span><br /><script>//create json object on the flyvar jsonObject= {"bookstore":[{ "book":{ "title": "Learning XML", "author": "Sam R. Samsonite", "year": "2003", "price": "39.95" }}, {"book":{ "title": "Learning ABC", "author": "Raimo R. Reader", "year": "2011", "price": "70.00" } } ]};document.getElementById("jtitle1").innerHTML=jsonObject.bookstore[0].book.title;....document.getElementById("jtitle2").innerHTML=jsonObject.bookstore[1].book.title;</script>

Page 11: JSON – AJAX - REST JavaScript Object Notation

JSON.parse is safe

eval() does NOT check if unwanted string embedded (DON’T USE)

• To convert a JSON text into an object, you can use the eval() function. eval() invokes the JavaScript compiler. Since JSON is a proper subset of JavaScript, the compiler will correctly parse the text and produce an object structure.

• var myObject = eval('(' + myJSONtext + ')'); The eval function is very fast. However, it can compile and execute any JavaScript program, so there can be security issues. The use of eval is indicated when the source is trusted and competent. It is much safer to use a JSON parser.

Page 12: JSON – AJAX - REST JavaScript Object Notation

JSON.parse example//serialized object in json format//REM. string continued with concatenate operator +var jsonTxt= ' {"bookstore":{'+ '"book":{'+ '"title": "Learning XML",'+ '"author": "Sam R. Samsonite",'+ '"year": "2003",'+ '"price": "39.95"'+ '}'+ '}'+ '}';//deserialized objectvar jsonObject = JSON.parse(jsonTxt);

document.getElementById("jtitle").innerHTML=jsonObject.bookstore.book.title;document.getElementById("jauthor").innerHTML=jsonObject.bookstore.book.author;document.getElementById("jyear").innerHTML=jsonObject.bookstore.book.year;document.getElementById("jprice").innerHTML=jsonObject.bookstore.book.price;

Page 13: JSON – AJAX - REST JavaScript Object Notation

Optimazing Json {"bookstore":[

{"book":{ "title": "Learning XML", "author": "Sam R. Samsonite", "year": "2003", "price": "39.95" }}, {"book":{ "title": "Learning XHTML", "author": "Ted T. Terrible", "year": "2005", "price": "15.60" }}, {"book":{ "title": "Learning ABC", "author": "Raimo R. Reader", "year": "2011", "price": "70.00" }} ] }

{"bookstore":[

{ "title": "Learning XML", "author": "Sam R. Samsonite", "year": "2003", "price": "39.95" }, { "title": "Learning XHTML", "author": "Ted T. Terrible", "year": "2005", "price": "15.60" }, { "title": "Learning ABC", "author": "Raimo R. Reader", "year": "2011", "price": "70.00" } ] }

jsonObject.bookstore[0].book.title;jsonObject.bookstore[0].title

Page 14: JSON – AJAX - REST JavaScript Object Notation

Comparing XML and JsonJSON

Pro:Simple syntax, which results in less "markup" overhead compared to XML.Easy to use with JavaScript as the markup is a subset of JS object literal notation and has the same basic data types as JavaScript.Con:Simple syntax, only a handful of different data types is supported.

XMLPro:Generalized markup, it is possible to create "dialects" for any kind of purposeXML Schema for datatype, structure validation. Makes it also possible to create new datatypes.XSLT for transformation into different output formats.XPath/XQuery for extracting information (which makes getting information in deeply nested structures much easier then with JSON).Con:Relatively wordy compared to JSON (results in more data for the same amount of information).

Page 15: JSON – AJAX - REST JavaScript Object Notation

AjaxAjax is an acronym for Asynchronous JavaScript (and XML) is a group of interrelated web development techniques used on the client-side to create asynchronous web applications. With Ajax, web applications can send data to, and retrieve data from, a server asynchronously (in the background) without interfering with the display and behavior of the existing page.

Data can be retrieved using the XMLHttpRequest object. Despite the name, the use of XML is not required (JSON is often used instead), and the requests do not need to be asynchronous.

Ajax is not a single technology, but a group of technologies. HTML and CSS can be used in combination to mark up and style information. The DOM is accessed with JavaScript to dynamically display, and to allow the user to interact with the information presented.

JavaScript and the XMLHttpRequest object provide a method for exchanging data asynchronously between browser and server to avoid full page reloads.

Page 16: JSON – AJAX - REST JavaScript Object Notation

PHP and JSON

Parsing JSON with PHP

Serializing/deserializing JSON with PHPhttp://www.php.net/manual/en/book.json.php

http://developer.yahoo.com/php/howto-parseRestPhp.html

Page 17: JSON – AJAX - REST JavaScript Object Notation

AJAX – JSON - PHP

http://www.tutorialswitch.com/web-development/quick-and-simple-ajax-forms-with-json-responses/

$response = array('type'=>'', 'message'=>'');$response['type'] = 'success';$response['message'] = 'Thank-You for submitting the form!';echo json_encode($response);

Page 18: JSON – AJAX - REST JavaScript Object Notation

Representational State Transfer REST

• Representation– Bytes that present a resource, URL

• State– A resourse has a state at server– A client application has a state

• Transfer– Client Applications transfer state to server in order to update

server’s resource state– Client applications get states from the server to update its oen state

A style of software archetecture for distributed systems. Twitter, Flickr and Amazon expose data using REST

Page 19: JSON – AJAX - REST JavaScript Object Notation

Open APIs State of the Market

http://blog.programmableweb.com/2010/08/13/api-anti-patterns-how-to-avoid-common-rest-mistakes/

Page 20: JSON – AJAX - REST JavaScript Object Notation

REST vs. SOAPtechnology

Page 21: JSON – AJAX - REST JavaScript Object Notation

RESTApi and Client

$user_list= array(array("id" => 1, "name" => "Simon"), array("id" => 2, "name" => "Zannetie"), array("id" => 3, "name" => "Carbonnel"));

exit(json_encode($user_list)); //array to JSON string

$user_listReq = file_get_contents('http://localhost/aaXMLandMCP/t27/api.php?action=get_user_list'); $user_list = json_decode($user_listReq, true); //JSON string back to array

client.php

api.phphttp/https

Page 22: JSON – AJAX - REST JavaScript Object Notation

json_decode

Serializing JSON string to JSON object or back associative array .When TRUE, returned objects will be converted into associative arrays.

$student_infoReq = file_get_contents('http://users.metropolia.fi/~karita/MCP/t26/api.php?action=get_student_list'); $student_info = json_decode($student_infoReq, true);

$student_info = json_decode($student_infoReq, false);

Page 23: JSON – AJAX - REST JavaScript Object Notation

REST vs. SOAPlanguages