JSON By Marcus Lopes Summary • • • • • What is JSON? JSON vs XML Using JSON JSON + AJAX JSON + JQuery What is JSON? • • • • Javascript Object Notation RFC 4627 Lightweight alternative to XML Built-in to Javascript JSON Structure • Object Pair of curly brackets containing zero or more name/value pairs.E.g.: { "customer": { "name":"Marcus", "favoriteFood":"Burgers", "age": 21 } } To find out the name for this customer, you would write: customer.name JSON Structure • Arrays Represented as square brackets and values are separated by comas. May contain 0 or more values.E.g.: {"customer": { "name":"Marcus", "favoriteFood":[ "Burgers","Fries","Bacon"], "age": 21 } } customer.favoriteFood[2] would return Bacon JSON Structure • Numbers Similar to most programming languages E.g.: {"customer": { "name":"Marcus", "numbers":[ 23, 2, 1.35], "age": 21 } } To find the age, you can type customer.age JSON Structure • Strings Work similar to the C family of programming languages A string begins and ends with quotation marks. E.g.: {"customer": { "name":"Marcus", "language":"Portuguese" } } To find out the language, you can type customer.language JSON Structure • Objects JSON objects can contain nested objects and functions: {"customer": { "myFunction":function (){alert("Hello world!");}, "numbers":[23, 2, 1.35], "age": 21 } } To call the method myFunction, you can type customer.myFunction(); JSON Structure • Parsing The default encoding for JSON is UTF-8 • According to its documentation, JSON shall be encoded in Unicode. • In order to read JSON from an AJAX request, we must evaluate the JSON code using the eval() function. • Parenthesis must surround the code to be evaluated to avoid confusion between a code block and an object E.g.: eval("({price:20})") Links Response: HTML, XML or JSON http://www.quirksmode.org/blog/archives/2005/12/the_ajax_res pon.html JSON documentation http://www.json.org/ PHP json_encode documentation http://php.net/manual/en/function.json-encode.php