Presentation is loading. Please wait.

Presentation is loading. Please wait.

JSON – AJAX - REST JavaScript Object Notation

Similar presentations


Presentation on theme: "JSON – AJAX - REST JavaScript Object Notation"— Presentation transcript:

1 JSON – AJAX - REST JavaScript Object Notation

2 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. 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.

3 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)

4 innerHTML Manufacturer: Operating system: Released: Type: Apps: var JSONObject = { "manufacturer":"Jolla Ltd", "os":"Sailfish", "released":" ", "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; 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.

5 XML JSON Employees Mary Programmer Web html 12 Ted Technology Electronics Embedded systems 12 REM: EXTRA SPACES MIGHT APPEAR!! Employees Mary Programmer Web html 12 Ted Technology Electronics Embedded systems 12 REM: EXTRA SPACES MIGHT APPEAR!! { "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" } ] } { "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" } ] }

6 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 validator { "bookstore":{ "book":{ "title": "Learning XML", "author": "Sam R. Samsonite", "year": "2003", "price": "39.95" } JSON validator Learning XML Sam R. Samsonite Learning XML Sam R. Samsonite 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

7 Like / Unlike XML Like 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 Like 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

8 Json Object is written inside curly brackets var jsonObject = { "anObject": { "numericProperty": -122, "stringProperty": "An offensive \" is problematic", "nullProperty": null, "booleanProperty": true, "dateProperty": " " }, " 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 pairs Data is separated by comma Curly brackets holds objects Square brackets holds arrays JSON syntax is a subset of the JavaScript object notation syntax. Data is in name/value pairs Data is separated by comma Curly brackets holds objects Square 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 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).

9 JSON Object creation JSON Object Creation in JavaScript Title: Author: Year: Price: //create json object on the fly var 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

10 Array of Objects Title:.. Title: //create json object on the fly var 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;

11 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. 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.

12 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 object var 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;

13 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

14 Comparing XML and Json JSON 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. XML Pro: Generalized markup, it is possible to create "dialects" for any kind of purpose XML SchemaXML Schema for datatype, structure validation. Makes it also possible to create new datatypes. XSLTXSLT for transformation into different output formats. XPathXPath/XQuery for extracting information (which makes getting information in deeply nested structures much easier then with JSON).XQuery Con: Relatively wordy compared to JSON (results in more data for the same amount of information). JSON 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. XML Pro: Generalized markup, it is possible to create "dialects" for any kind of purpose XML SchemaXML Schema for datatype, structure validation. Makes it also possible to create new datatypes. XSLTXSLT for transformation into different output formats. XPathXPath/XQuery for extracting information (which makes getting information in deeply nested structures much easier then with JSON).XQuery Con: Relatively wordy compared to JSON (results in more data for the same amount of information).

15 Ajax Ajax 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.AsynchronousJavaScriptXMLweb developmentclient-sideweb applicationsserver 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. XMLHttpRequest objectJSONasynchronous 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.HTMLCSSDOM JavaScript and the XMLHttpRequest object provide a method for exchanging data asynchronously between browser and server to avoid full page reloads.

16 PHP and JSON Parsing JSON with PHP Serializing/deserializing JSON with PHP

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

18 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 A style of software archetecture for distributed systems. Twitter, Flickr and Amazon expose data using REST

19 Open APIs State of the Market anti-patterns-how-to-avoid-common-rest-mistakes/

20 REST vs. SOAP technology

21 REST Api 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_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 $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.php http/https

22 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'); true $student_info = json_decode($student_infoReq, true); $student_infoReq = file_get_contents('http://users.metropolia.fi/~karita/MCP/t26/api.php?action=get_student_list'); true $student_info = json_decode($student_infoReq, true);, false $student_info = json_decode($student_infoReq, false);

23 REST vs. SOAP languages


Download ppt "JSON – AJAX - REST JavaScript Object Notation"

Similar presentations


Ads by Google