Presentation is loading. Please wait.

Presentation is loading. Please wait.

JavaScript Object Notation

Similar presentations

Presentation on theme: "JavaScript Object Notation"— Presentation transcript:

1 JavaScript Object Notation
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.

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":" ", "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. 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.", "width": "800" }

5 XML <-> JSON
<?xml version="1.0" encoding="ISO "?> <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> <firstname>Ted</firstname> <surname>Technology</surname> <field>Electronics</field> <skillname>Embedded systems</skillname> </reqistry> REM: EXTRA SPACES MIGHT APPEAR!! { "reqistry":{ "usage": "Employees", "expert":[ "person":{ "firstname": "Mary", "surname": "Programmer" }, "expertise":{ "field": "Web", "skillname": "html", "years": "12" } "firstname": "Ted", "surname": "Technology" "field": "Electronics", "skillname": "Embedded systems", ]

6 JSON Syntax { "bookstore":{ "book":{ "title": "Learning XML", "author": "Sam R. Samsonite", "year": "2003", "price": "39.95" } JSON validator <?xml version="1.0" encoding="ISO "?> <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 Unlike 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 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"); document.getElementById("jauthor"); document.getElementById("jyear"); document.getElementById("jprice") </script> ", "width": "800" }

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> ", "width": "800" }

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.

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"); document.getElementById("jauthor"); document.getElementById("jyear"); document.getElementById("jprice");

13 Optimazing Json jsonObject.bookstore[0].book.title;
{"bookstore":[ {"book":{ "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" }} ] } {"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 XML 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 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). 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. 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.

16 PHP and JSON
Serializing/deserializing JSON with PHP 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);

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

19 Open APIs State of the Market

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

23 REST vs. SOAP languages

Download ppt "JavaScript Object Notation"

Similar presentations

Ads by Google