The document provides an introduction to JSON (JavaScript Object Notation). It explains that JSON is a lightweight data format that is easy for humans to read and write, and for machines to parse and generate. JSON is used primarily to transmit data between a web server and web application. It describes JSON syntax, values, and compares JSON to XML.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
263 views24 pages
JSON
The document provides an introduction to JSON (JavaScript Object Notation). It explains that JSON is a lightweight data format that is easy for humans to read and write, and for machines to parse and generate. JSON is used primarily to transmit data between a web server and web application. It describes JSON syntax, values, and compares JSON to XML.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24
{“JSON”:”JavaScript Object Notation”}
JSON - Introduction
● JSON stands for JavaScript Object This example is a JSON string:
Notation '{"name":"John", "age":30, ● JSON is a text format for storing "car":null}' and transporting data ● JSON is "self-describing" and easy It defines an object with 3 properties: to understand ● name, age, car ● JSON is a lightweight data- Each property has a value. interchange format If you parse the JSON string with a JavaScript ● JSON is language independent program, you can access the data as an object:
let personName = obj.name;
let personAge = obj.age; JSON Syntax
JSON syntax is derived from JavaScript
JSON Values object notation syntax: ● a string ● Data is in name/value pairs ● a number ● Data is separated by commas ● an object ● Curly braces hold objects ● an array ● Square brackets hold arrays ● a boolean A name/value pair consists of a field ● null name (in double quotes), followed by a In JavaScript values can be all of the above, plus colon, followed by a value: any other valid JavaScript expression, including:
{"name":"John"} ● a function ● a date ● undefined JavaScript Objects
person = {name:"John", age:31, city:"New York"};
// ACCESSING OBJECTS // LOOPING OBJECTS
const myObj = JSON.parse(person); Person.name; // returns John
Person["name"]; // returns John
let text = ""; // MODIFYING OBJECTS for (const x in myObj) { person.name = "Gilbert"; text += x + ", ";
person["name"] = "Gilbert"; }
● The file type for JSON files is ".json"
● The MIME type for JSON text is "application/json" Link to JSON Array JSON vs XML
JSON is Like XML Because JSON is Unlike XML Because
● Both JSON and XML are "self ● JSON doesn't use end tag describing" (human readable) ● JSON is shorter ● Both JSON and XML are ● JSON is quicker to read and write hierarchical (values within values) ● JSON can use arrays ● Both JSON and XML can be parsed The biggest difference is: and used by lots of programming languages XML has to be parsed with an XML ● Both JSON and XML can be fetched parser. JSON can be parsed by a with an XMLHttpRequest standard JavaScript function. JSON Data Types
data to/from a web server. JSON.parse('{"name":"John", "age":30, "city":"New York"}'); When receiving data from a web server, the data is always a string. Use the JavaScript object in web page:
Parse the data with JSON.parse(), and <p id="demo"></p>
the data becomes a JavaScript object. <script> When we receive text from web server. document.getElementById("demo").inn Use the JavaScript function erHTML = obj.name; JSON.parse() to convert text into a JavaScript object </script> JSON.parse() - Array as JSON
When using the JSON.parse() on a const text = '{"name":"John",
JSON derived from an array, the "birth":"1986-12-14", "city":"New method will return a JavaScript array, York"}'; instead of a JavaScript object. const obj = JSON.parse(text); Exceptions :Parsing Dates obj.birth = new Date(obj.birth); Date objects are not allowed in JSON. document.getElementById("demo").inn If you need to include a date, write it erHTML = obj.name + ", " + obj.birth; as a string.
You can convert it back into a date
object later: JSON.parse() - reviver
you can use the second parameter, of the JSON.parse() function, called reviver. The reviver parameter is a function that checks each property, before returning the value.
const text = '{"name":"John", "birth":"1986-12-14", "city":"New York"}';
'{"name":"John", "age":30, "car":null}' ● Inside the JSON string there is a JSON object literal: {"name":"John", "age":30, "car":null} ● JSON object literals are surrounded by curly braces {}. ● JSON object literals contains key/value pairs. ● Keys and values are separated by a colon. ● Keys must be strings, and values must be a valid JSON data type ● Each key/value pair is separated by a comma. ● you create a JavaScript object by parsing a JSON string ...Example JSON Array Literals
● Arrays in JSON are almost the same as arrays in JavaScript.
● In JSON, array values must be of type string, number, object, array, boolean or null. ● In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.
document.getElementById("demo").innerHTML = myObj.cars[0]; JSON Server (Not included in 8EC07)
Sending Data : If you have data stored in a JavaScript object, you can convert the object into JSON, and send it to a server: const myObj = {name: "John", age: 31, city: "New York"}; const myJSON = JSON.stringify(myObj); window.location = "demo_json.php?x=" + myJSON;
Receiving Data : If you receive data in JSON format, you can easily convert it into a JavaScript object: const myJSON = '{"name":"John", "age":31, "city":"New York"}'; const myObj = JSON.parse(myJSON); document.getElementById("demo").innerHTML = myObj.name; JSON From a Server (Not included in 8EC07)
You can request JSON from the server by using an AJAX request
As long as the response from the server is written in JSON format, you can parse the string into a JavaScript object.
Use the XMLHttpRequest to get data from the server: json_demo.txt
{ const xmlhttp = new XMLHttpRequest(); "name":"John", xmlhttp.onload = function() { "age":31, "pets":[ const myObj = JSON.parse(this.responseText); { "animal":"dog", document.getElementById("demo").innerHTML = myObj.name; "name":"Fido" }, }; { "animal":"cat", "name":"Felix" }, xmlhttp.open("GET", "json_demo.txt"); ] xmlhttp.send(); } JSON PHP (Not included in 8EC07) (Not included in 8EC07)
<script> function change_myselect(sel) { const dbParam = JSON.stringify({table:sel,limit:20}); const xmlhttp = new XMLHttpRequest(); …next JSON HTML …json_demo_html_option.php - Continued
xmlhttp.onload = function() { const myObj = JSON.parse(this.responseText); let text = "<table border='1'>" for (let x in myObj) { text += "<tr><td>" + myObj[x].name + "</td></tr>"; } text += "</table>" document.getElementById("demo").innerHTML = text; } xmlhttp.open("POST", "json_demo_html_table.php"); xmlhttp.setRequestHeader("Content-type", "application/x-www-form- urlencoded"); xmlhttp.send("x=" + dbParam); } </script> JSONP
● JSONP is a method for sending JSON data without worrying about cross- domain issues. ● JSONP does not use the XMLHttpRequest object. ● JSONP uses the <script> tag instead. ● JSONP stands for JSON with Padding. ● JSONP works only with GET
<script> function clickButton() { let s = document.createElement("script"); s.src = "demo_jsonp.php"; document.body.appendChild(s); } function myFunc(myObj) { document.getElementById("demo").innerHTML = myObj.name; } </script> </body> </html> Dynamic JSONP Result Make the example dynamic by sending JSON to the php file, and let the php file return a JSON object based on the information it gets.
PHP File explained:
● Convert the request into an object, using the PHP function json_decode(). ● Access the database, and fill an array with the requested data. ● Add the array to an object. ● Convert the array into JSON using the json_encode() function. ● Wrap "myFunc()" around the return object. Dynamic JSONP Result … Continued <?php header("Content-Type: application/json; charset=UTF-8"); $obj = json_decode($_GET["x"], false);
$conn = new mysqli("myServer", "myUser", "myPassword", "Northwind");
$result = $conn->query("SELECT name FROM ".$obj->$table." LIMIT ".$obj- >$limit); $outp = array(); $outp = $result->fetch_all(MYSQLI_ASSOC);
echo "myFunc(".json_encode($outp).")"; ?> Dynamic JSONP Result … Continued
The "myFunc" function will be called from the php file
const obj = { table: "products", limit: 10 }; let s = document.createElement("script"); s.src = "jsonp_demo_db.php?x=" + JSON.stringify(obj); document.body.appendChild(s);
function myFunc(myObj) { let txt = ""; for (let x in myObj) { txt += myObj[x].name + "<br>"; } document.getElementById("demo").innerHTML = txt; } JSONP : Callback Function
When you have no control over the server file, how do you get the server file to call the correct function?
Sometimes the server file offers a callback function as a parameter