0% found this document useful (0 votes)
442 views

JSON Lecture PDF

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and for machines to parse and generate. It is built on two structures: a collection of name/value pairs and an ordered list of values. JSON is primarily used to transmit data between a web server and web application, and is widely used by APIs and for storing/exchanging data. The document provides an introduction and overview of JSON, including its structure, syntax, examples, and how to encode and decode JSON in PHP using json_encode() and json_decode() functions.

Uploaded by

Jhunly Faderagao
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
442 views

JSON Lecture PDF

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and for machines to parse and generate. It is built on two structures: a collection of name/value pairs and an ordered list of values. JSON is primarily used to transmit data between a web server and web application, and is widely used by APIs and for storing/exchanging data. The document provides an introduction and overview of JSON, including its structure, syntax, examples, and how to encode and decode JSON in PHP using json_encode() and json_decode() functions.

Uploaded by

Jhunly Faderagao
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Web Programming

Introduction to JSON

http://php.net/manual/en/function.json-decode.php
https://www.javatpoint.com/ajax-tutorial
https://www.w3resource.com/JSON/introduction.php
What is JSON

• JSON stands for JavaScript Object Notation


• JSON is lightweight data-interchange format
• JSON is easy to read and write than XML
• JSON is language independent
• JSON supports array, object, string, number and values
What is JSON

JSON is often used to serialize and transfer data over a network


connection, for example between the web server and a web
application.

In computer science, serialization is a process to transforming data


structures and objects in a format suitable to be stored in a file or
memory buffer or transmitted over a network connection. Later on,
this data can be retrieved.

Because of the very nature of the JSON, it is useful for storing or


representing semi structured data.

Internet media type of JSON is "application/json".


Introduction to JSON
JSON Example:

The JSON file must be save with .json extension name

File: myfile.json

{"employees":[
{"name":"Gianne Mae", "email":"[email protected]"},
{"name":"Juan Paolo", "email":"[email protected]"},
{"name":"Sita", "email":"[email protected]"}
]}
Introduction to JSON
Features of JSON

1. Simplicity
2. Openness
3. Self Describing
4. Internationalization
5. extensibility
6. Interoperability
Introduction to JSON
No. JSON XML
JSON vs XML
JSON stands for JavaScript Object
1 XML stands for eXtensible Markup Language
Notation

2 JSON is simple to read and write XML is less simple than JSON

3 JSON is easy to learn XML is less easy to learn than JSON

4 JSON is data oriented XML is document-oriented

JSON doesn't provide display XML provides the capability to display data
5
capabilities because it is a markup language

6 JSON supports array XML doesn't support array

7 JSON is less secured than XML xml is more secured

JSON files are more human


8 XML files are less human readable
readable than XML

XML support many data types such as text,


JSON supports only text and number, images, charts, graphs, etc. Moreover,
9
number data type XML offers options for transferring the format or
structure of data with actual data
Introduction to JSON
JSON vs XML
JSON Example
{"employees":[
{"name":"Gianne Mae", "email":"[email protected]"},
{"name":"Juan Paolo", "email":"[email protected]"},
{"name":"Sita", "email":"[email protected]"}
]}

XML Example
<employees>
<employee>
<name>Gianne Mae</name>
<email>[email protected]</email>
</employee>
<employee>
<name>Juan Paolo</name>
<email>[email protected]</email>
</employee>
<employee>
<name>Sita</name>
<email>[email protected]</email>
</employee>
</employees>
Introduction to JSON
Structure of JSON
Introduction to JSON
Similarities between JSON and XML

• Both are simple and open


• Both supports unicode. So internationalization is supported by JSON and
XML both
• Both represents self describing data
• Both are interoperable or language-independent
Introduction to JSON
JSON Object
A JSON object contains data in the form of key/value pair. The keys are strings and the
values are the JSON types. Keys and values are separated by colon (:). Each entry
(key/value pair) is separated by comma.

The {} (curly brace) represents the JSON object.

JSON Object Example:


{
"employee": {
"name":"boyet",
"salary":56000,
"married":true
}
}
Introduction to JSON
JSON Array
The [] (square bracket) represents the JSON array. A JSON array can have values and
objects.

JSON Array Example:


This is an example of JSON array having values.
["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]

This is an example of JSON array having objects.


[
{"name":"Angel Locsin", "email":"[email protected]"},
{"name":"Ellen Adarna", "email":"[email protected]"}
]
Introduction to JSON
JSON More Example
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onClick": "CreateDoc()"},
{"value": "Open", "onClick": "OpenDoc()"},
{"value": "Save", "onClick": "SaveDoc()"}
]
}
}}
The XML representation of above JSON example is given below.
<menu id="file" value="File">
<popup>
<menuitem value="New" onClick="CreateDoc()" />
<menuitem value="Open" onClick="OpenDoc()" />
<menuitem value="Save" onClick="SaveDoc()" />
</popup>
</menu>
Introduction to JSON
JSON Object with Strings

The string value must be enclosed within double quote.


{
"name":"boypogi",
"email":"[email protected]"
}

JSON Object with Numbers

JSON supports numbers in double precision floating-point format. The number can be
digits (0-9), fractions(.33, .532 etc) and exponent (e, e+, e-, E, E+, E-).

{
"integer": 34,
"fraction": .2145,
"exponent": 6.61789e+0
}
Introduction to JSON
JSON Object with Booleans

JSON also supports boolean values true or false.


{
"first": true,
"second": false
}
Introduction to JSON
JSON Object with Nested Object

A JSON object can have another object also.


{
"firstName": "Ramon",
"lastName": "Bautista",
"age": 27,
"address" : {
"StreetAddress": "Maile Bldg, Maui Oasis Anonas St.",
"city": "Manila",
"Region": "NCR",
"ZipCode": "1014"
}
}
Introduction to JSON
JSON Array of Strings

A JSON arrays storing string values

["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",


"Friday", "Saturday"]

JSON Array of Numbers

A JSON arrays storing number values

[12, 34, 56, 43, 95]

JSON Array of Booleans

A JSON arrays storing boolean values

[true, true, false, false, true]


Introduction to JSON
JSON Array of Objects

A JSON array having 4 objects.


{"employees":[
{"name":"Sam", "email":"[email protected]", "age":23},
{"name":"Yam", "email":"[email protected]", "age":28},
{"name":"Tim", "email":"[email protected]", "age":33},
{"name":"Bob", "email":"[email protected]", "age":41}
]}

JSON Multidimensional Array

We can store array inside JSON array, it is known as array of arrays or multi-dimentional
array.
[
[ "a", "b", "c" ],
[ "m", "n", "o" ],
[ "x", "y", "z" ]
]
Introduction to JSON
JSON Comments

JSON doesn’t support comments. It is not a standard.


But you can do some tricks such as adding extra attribute for comment in JASON object.

For example.
{
"employee":{
"name":"Mhen",
"salary":56000,
"comments":"He is a nice man"
}
}

Here, “comments” attribute can be treated as comment.


Introduction to JSON
PHP JSON
PHP allows you to encode and decode JSON by using
json_encode() and json_decode() functions.

The json_encode() function returns the JSON representation of a value. It converts PHP
variable (containing array) into JSON.

Syntax:
string json_encode ( mixed $value [, int $options = 0
[, int $depth = 512 ]] )
Introduction to JSON
PHP JSON

json_encode example no. 1

Example to encode JSON


<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>

Output:

{"a":1,"b":2,"c":3,"d":4,"e":5}
Introduction to JSON
PHP JSON

json_encode example no. 2

Example to encode JSON


<?php
$arr2 = array('firstName' => 'Joey', 'lastName' => 'De
Leon', 'email' => '[email protected]');
echo json_encode($arr2);
?>

Output:

{"firstName":"Joey","lastName":"De Leon","email":"[email protected]"}
Introduction to JSON
PHP JSON

PHP json_decode
The json_decode() function decodes the JSON string. In other words, It converts JSON
string into a PHP variable.

Syntax:

mixed json_decode ( string $json [, bool $assoc = false [, int


$depth = 512 [, int $options = 0 ]]] )

mixed indicates that a


parameter may accept
multiple (but not
necessarily all) types.
Introduction to JSON
PHP JSON

PHP json_decode example no. 1

Example to decode JSON string.


<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json, true));
//true means returned object will be converted into associative
array
?>
Output (True)
Introduction to JSON
PHP JSON

PHP json_decode example no. 1

Example to decode JSON string.


<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json, false));
//true means returned object will be converted into associative
array
?>
Output (False)
Introduction to JSON
PHP JSON

PHP json_decode example no. 2

Example to decode JSON string.


<?php
$json2 = '{"firstName" : "James", "lastName" : "Reid", "email
" : "[email protected]"}';
var_dump(json_decode($json2, true));
?>
Output (True) Output (False)
Introduction to JSON
Loading JSON Data in PHP
<!doctype html>
<html>
<head>
<title>JSON Data in PHP</title>
</head>
<body>
<br>
<h3 align="">How to Load JSON Data in PHP</h3><br>
<h4>Video Title</h4>
file: search_json_data.php
<?php
$data = file_get_contents("video.json");
$data = json_decode($data);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
</body>
</html>
Introduction to JSON
Loading JSON Data in PHP file: video.json
[ {"video_title":"Export MySQL data to Excel in PHP - PHP Tutorial"},
{"video_title":"Live Table Add Edit Delete using Ajax jQuery in PHP
MySQL"},
{"video_title":"Make SEO Friendly or Clean URL in PHP using
.htaccess"},
{"video_title":"How to Add Watermark to an Image using PHP GD
Library"},
{"video_title":"Create Simple Image using PHP"},
{"video_title":"How to check Multiple value exists in an Array in
PHP"},
{"video_title":"How to merge two PHP JSON Array"},
{"video_title":"How to Insert Data Using Stored Procedure in Php
MySQL"},
{"video_title":"How to check Username availability using PHP, Ajax,
Jquery and MySQL"},
{"video_title":"Rename uploaded image in php with upload validation"},
{"video_title":"Auto Refresh Div Content Using jQuery and Ajax"},
{"video_title":"Insert Update Delete using Stored Procedure in MySQL
and PHP"}]
Introduction to JSON
Loading JSON Data in PHP Output:
Introduction to JSON
Loading JSON Data in PHP
<!doctype html>
<html>
<head>
<title>JSON Data in PHP</title>
</head>
<body>
<br>
<h3 align="">How to Load JSON Data in PHP</h3><br>
<h4>Video Title</h4>
file: search_json_data.php
<?php
$data = file_get_contents("video.json");
$data = json_decode($data, true);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
</body>
</html>
Introduction to JSON
Loading JSON Data in PHP Output:
Introduction to JSON
Loading JSON Data in PHP
<!doctype html>
<html>
<head>
<title>JSON Data in PHP</title>
</head>
<body>
<br>
<h3 align="">How to Load JSON Data in PHP</h3><br>
<h4>Video Title</h4>
<?php file: search_json_data.php
$data = file_get_contents("video.json");
$data = json_decode($data, true);
foreach($data as $row)
{ echo $row["video_title"].'<br>';}
?>
</body>
</html>
Introduction to JSON
Loading JSON Data in PHP Output:
Introduction to JSON
JSON Data to MySQL Output:
<?php
$connect = mysqli_connect("localhost","root","","maindb");
$filename = "employee.json";
$data = file_get_contents($filename);
$array = json_decode($data, true);
foreach($array as $row)
{
$sql = "INSERT INTO employee (id, name, gender, designation)
VALUES('".$row["id"]."','".$row["name"]."','".$row["gender"]."','
".$row["designation"]."')";
mysqli_query($connect,$sql);
}
echo "Employee data inserted";
?>
Introduction to JSON
JSON Data to MySQL Output:
Introduction to JSON
JSON.parse()

• A common use of JSON is to exchange data to/from a web server.


• When receiving data from a web server, the data is always a string.
• Parse the data with JSON.parse(), and the data becomes a
JavaScript object.
Introduction to JSON
JSON.parse()
Example:
Suppose that we received this text from a web server
"name": "Juan", "age": 27, "address": "Sta. Mesa, Manila"}
<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p id='demo'></p>
<script>
var txt = '{"name": "Juan", "age": 27, "address": "Sta.
Mesa, Manila"}'
var obj = JSON.parse(txt);
document.getElementById("demo").innerHTML=obj.name + ", "
+ obj.age;
</script>
</body>
</html>
Introduction to JSON
Example:
<!DOCTYPE html>
<html>
<body>
<h2>Use the XMLHttpRequest to get the content of a file. </h2>
<p>The content is written in JSON format, and can easily be converted
into a JavaScript object.</p>
<p id='demo'></p>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;}};
xmlhttp.open("GET", "json.txt", true);
xmlhttp.send();
</script>
<p>Click this link to see the file <a href="json.txt"
target="_blank">json.txt</a></p>
</body>
</html>
Introduction to JSON

XMLHttpRequest Object can be used to exchange data with a server


behind the scenes.
This means that it is possible to update parts of a web page, without
reloading the whole page.
Syntax for creating XMLHttpRequest object:
variable = new XMLHttpRequest();
Introduction to JSON
XMLHttpRequest Object Properties
Method Description
New XMLHttpRequest() Creates a new XMLHttpRequest object
Abort() Cancels the current request
getAllResponseHeaders() Returns header information
getResponseHeader() Returns specific header information
Open(method,url,asyn,user,psw) Specifies the request
method: the request type GET or POST
url: the file location
async: true(async) or false(sync)
user: optional user name
psw: optional password
send() Sends the request to the server
Used for GET requests
send(string) Sends the request to the server
Used for POST requests
setRequestHeaderr() Adds a label/value pair to the header to be sent
Introduction to JSON
XMLHttpRequest Object Properties
Property Description
Onreadystatechange Defines a function to be called when the readyState property changes
readyState Holds the status of the XMLHttpRequest
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
responseText Returns the response data as a string
responseXML Returns the response data as XML data
Status Returns the status-number of a request
200: “OK”
403: “Forbidden”
404: “Not Found”
statusText Returns the status-text(e.g. “OK” or “Not Found”)
Introduction to JSON
Parsing Dates
Date objects are not allowed in JSON. You need to write it as a string If you need to include a
date.

<!DOCTYPE html>
<html>
<body>
<h2>Convert a string into a date object.</h2>
<p id="demo"></p>
<script>
var text = '{"name":"Joselito", "birth":"1965-08-06",
"address":"Sta. Mesa, Manila"}';
var obj = JSON.parse(text);
obj.birth = new Date(obj.birth);
document.getElementById("demo").innerHTML = obj.name + ", "
+obj.birth;
</script>
</body>
</html>
Introduction to JSON
Parsing Dates
Other solution for date using the second parameter of the JSON.parse() function, called reviver.
The reviver parameter is a function that checks each property, before returning the value.
<!DOCTYPE html>
<html>
<body>
<h2>Convert a string into a date object.</h2>
<p id="demo"></p>
<script>
var text = '{"name":"Joselito", "birth":"1965-08-06", "city":"Sta. Mesa,
Manila"}';
var obj = JSON.parse(text, function (key, value) {
if (key == "birth") {
return new Date(value);
} else {
return value;
}
});
document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth;
</script>
</body>
</html>
Introduction to JSON
JSON.stringify()

• A common use of JSON is to exchange data to/from a web server.


• When sending data from a web server, the data has to be a string.
• Convert a JavaScript object into a string
Introduction to JSON
JSON.stringify()
Stringify a JavaScript Object
Suppose we have this object in JavaScript
var obj = {name:"Joselito", age:25, address:"Sta. Mesa, Manila"};

Use the JS function JSON.stringify() to convert it into a string.


var JSONstr = JSON.stringify(obj);

document.getElementById("demo").innerHTML = JSONstr;

The result will be a string


Introduction to JSON
JSON.stringify()

<!DOCTYPE html>
<html>
<body>
<h2>Create JSON string from a JavaScript object.</h2>
<p id="demo"></p>
<script>
var obj = { name: "Joselito", age: 25, city: "Sta. Mesa, Manila" };
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
</script>
</body>
</html>
Introduction to JSON
JSON.stringify()

Stringify a JavaScript Array


Suppose we have this array in JavaScript
var arrstr = [ "Enelra", "Rose", "Gianne", "Paolo" ];

Use the JS function JSON.stringify() to convert it into a string.


var JSONstr = JSON.stringify(arrstr);
document.getElementById("demo").innerHTML = JSONstr;

The result will be a string


Introduction to JSON
JSON.stringify()

<!DOCTYPE html>
<html>
<body>
<h2>Create JSON string from a JavaScript array.</h2>
<p id="demo"></p>
<script>
var arr = [ "Enelra", "Rose", "Gianne", "Paolo" ];
var JSONstr = JSON.stringify(arr);
document.getElementById("demo").innerHTML = JSONstr;
</script>
</body>
</html>
Introduction to JSON
JSON.HTML

• JSON can be very easily be translated into JavaScript


• JavaScript can be used to make HTML in your web pages

You might also like