1 / 23

JSON – AJAX - REST

JSON – AJAX - REST. JavaScript Object Notation http://www.json.org/ . JSON. JSON: J ava S cript O bject N otation JSON is syntax for storing and exchanging text information. Much like XML . JSON is smaller than XML, and faster and easier to parse. Json Object.

wattan
Download Presentation

JSON – AJAX - REST

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  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.

  3. Json Object {”persons": [{ "firstName":”Mary" , ”surName":”Pop" }, { "firstName":”Peter" , ”surName":”Pan" }, { "firstName":”Erkki" , ”surName":”Aalto" }]}object The persons object is an array of 3 personnel records (objects) 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.

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

  5. XML <-> JSON { "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" } } ] } } <?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> http://jsontoxml.utilities-online.info/ REM: EXTRA SPACES MIGHT APPEAR!!

  6. JSON Syntax { "bookstore":{ "book":{ "title": "Learning XML", "author": "Sam R. Samsonite", "year": "2003", "price": "39.95" } } } JSON validator http://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> Syntax for passing around objects that contain name/value pairs, arrays and other objects • 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

  8. Json Object is written inside curly brackets 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 var 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 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 <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 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 </script>

  10. Array of Objects Title: <span id="jtitle1"></span><br /> .. Title: <span id="jtitle2"></span><br /> <script> //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; </script>

  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. • varmyObject = 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":[ { "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; {"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" }} ] } 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 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).

  15. Ajax Ajax is an acronym for AsynchronousJavaScript (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 XMLHttpRequestobject. 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.

  16. PHP and JSON http://www.php.net/manual/en/book.json.php Serializing/deserializing JSON with PHP http://developer.yahoo.com/php/howto-parseRestPhp.html • Parsing 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); http://www.tutorialswitch.com/web-development/quick-and-simple-ajax-forms-with-json-responses/

  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

  19. Open APIs State of the Market http://blog.programmableweb.com/2010/08/13/api-anti-patterns-how-to-avoid-common-rest-mistakes/

  20. REST vs. SOAPtechnology

  21. 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 api.php http/https $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

  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'); $student_info = json_decode($student_infoReq, true); $student_info = json_decode($student_infoReq, false);

  23. REST vs. SOAPlanguages

More Related