Special Topic JSON
Introducing JSON JSON (JavaScript ObjectNotation): A data format based on the object literal format Advantage of JSON over XML – JSON is a terse language with a minimum of extraneous characters
JSON Preferable to XML Similar to XML Text file object { “isbn”:” ”, “price”:”15.00” }
Introducing JSON JSON documents can contain several layers of nested values Size of a JSON data file can be further reduced through the use of array literals Following this general approach, can add more nested fields and arrays to achieve complicated data structures
Introducing JSON Advantage of JSON over XML – Easier to retrieve specific data values with JSON; its data structures can be treated as custom JavaScript objects with data fields referenced as object properties Disadvantage of JSON over XML – Less readable by the layperson
Introducing JSON Reading a JSON object with JavaScript – To retrieve a document containing a JSON object: req.responseText – To convert JSON text into a JavaScript object: var jsonData = eval( "(" + req.responseText + ")" );
Can Nest Widgets Smith Blogs Harris { “books” { “book1” : { “title”: “Widgets”, “Author”: “Smith”, “Price”: “20.00” } “book2”: { “title”: “Blogs”, “Author”: “Harris”, “Price”: “20.00” }
Array Literals [ ] Widgets Smith Blogs Harris { “books” { “book”: { “Price”: “20.00”, “title”: [“Widgets”,“Blogs”], “Author”: [“Smith”, “Harris”] } }
Array Literals/iterations Widgets Smith Blogs Harris { “books” { “book”: [ { “Price”: “15.00”, “title”: [“Widgets”,“Blogs”], “Author”: [“Smith”, “Harris”], } { “Price”: “20.00”, “title”: [“HTML”,“CSS”], “Author”: [“Langley”, “Benson”], } ] }
How to use HTTPRequest /GET/ send(null) Receive object responseTEXT Assign result to a variable, using EVAL function The eval() function evaluates or executes an argument To convert JSON text into an object eval() invokes the JavaScript compiler var myBooks = this.responseText var myBooks = eval( "(" + this.responseText+ ")" ); myBooks.books.book[0].price