JSON
JSON
JSON - Introduction
{"name":"John"} ● a function
● a date
● undefined
JavaScript Objects
person["name"] = "Gilbert"; }
{"employees":[ <employees>
{ "firstName":"John", <employee>
"lastName":"Doe" }, <firstName>John</firstName>
{ "firstName":"Anna", <lastName>Doe</lastName>
"lastName":"Smith" }, </employee>
]} <employee>
<firstName>Anna</firstName>
<lastName>Smith</lastName>
</employee>
</employees>
JSON vs XML - Continued
● 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
string {"name":"John"}
boolean {"sale":true}
null {"middlename":null}
JSON.parse()
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.
Arrays in Objects
const myJSON = '{"name":"John", "age":30, "cars":["Ford", "BMW", "Fiat"]}';
const myObj = JSON.parse(myJSON);
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.
<?php
$myJSON = json_encode($myObj);
echo $myJSON;
$myJSON = json_encode($myArr);
echo $myJSON;
?>
JSON HTML …json_demo_html_table.php
<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
<!DOCTYPE html>
<html>
<body>
<button onclick="clickButton()">Click me!</button>
<p id="demo"></p>
JSONP … Continued
<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.
● 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);
echo "myFunc(".json_encode($outp).")";
?>
Dynamic JSONP Result … Continued
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?
let s = document.createElement("script");
s.src = "jsonp_demo_db.php?callback=myDisplayFunction";
document.body.appendChild(s);
function myDisplayFunction(myObj) {
document.getElementById("demo").innerHTML = myObj.name;