SlideShare a Scribd company logo
JSON Tutorial
JSON: JavaScript Object Notation.
JSON is a syntax for storing and exchanging data.
JSON is an easier-to-use alternative to XML.
JSON Example
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}
The following XML example also defines an
employees object with 3 employee records:
<employees>
<employee>
<firstName>John</firstName> <lastName>Doe</lastName>
</employee>
<employee>
<firstName>Anna</firstName> <lastName>Smith</lastName>
</employee>
<employee>
<firstName>Peter</firstName> <lastName>Jones</lastName>
</employee>
</employees>
JSON - Evaluates to JavaScript Objects
The JSON format is syntactically identical to the code for creating JavaScript objects.
Because of this similarity, instead of using a parser (like XML does), a JavaScript program can use
standard JavaScript functions to convert JSON data into native JavaScript objects.
JSON Example
<!DOCTYPE html>
<html>
<body>
<h2>JSON Object Creation in JavaScript</h2>
<p id="demo"></p>
<script>
var text = '{"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}';
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.name + "<br>" +
obj.street + "<br>" +
obj.phone;
</script>
</body>
</html>
JSON Syntax Rules
JSON syntax is derived from JavaScript object notation syntax:
Data is in name/value pairs
Data is separated by commas
Curly braces hold objects
Square brackets hold arrays
JSON Data - A Name and a Value
JSON data is written as name/value pairs.
A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a
value:
"firstName":"John"
JSON Objects
JSON objects are written inside curly braces.
Just like JavaScript, JSON objects can contain multiple name/values pairs:
{"firstName":"John", "lastName":"Doe"}
JSON Arrays
JSON arrays are written inside square brackets.
Just like JavaScript, a JSON array can contain multiple objects:
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter","lastName":"Jones"}
]
In the example above, the object "employees" is an array containing three objects. Each object is
a record of a person (with a first name and a last name).
JSON Uses JavaScript Syntax
Because JSON syntax is derived from JavaScript object notation, very little extra software is
needed to work with JSON within JavaScript.
With JavaScript you can create an array of objects and assign data to it, like this:
var employees = [
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter","lastName": "Jones"}
];
employees[0].firstName + " " + employees[0].lastName;
employees[0]["firstName"] + " " + employees[0]["lastName"];
A common use of JSON is to read data from a web server, and display the data in a web page.
For simplicity, this can be demonstrated by using a string as input (instead of a file).
JSON Example - Object From String
Create a JavaScript string containing JSON syntax:
var text = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';
JSON syntax is a subset of JavaScript syntax.
The JavaScript function JSON.parse(text) can be used to convert a JSON text into a JavaScript
object:
var obj = JSON.parse(text);
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>
Using eval()
Older browsers without the support for the JavaScript function JSON.parse() can use the eval()
function to convert a JSON text into a JavaScript object:
var obj = eval ("(" + text + ")");
JSON Http Request
A common use of JSON is to read data from a web server, and display the data in a web page.
This chapter will teach you, in 4 easy steps, how to read JSON data, using XMLHttp.
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '<a href="' + arr[i].url + '">' +
arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
</script>
Example Explained
1: Create an array of objects.
Use an array literal to declare an array of objects.
Give each object two properties: display and url.
Name the array myArray:
var myArray = [
{
"display": "JavaScript Tutorial",
"url": "http://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "http://www.w3schools.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "http://www.w3schools.com/css/default.asp"
}
]
2: Create a JavaScript function to display the array.
Create a function myFunction() that loops the array objects, and display the content as HTML
links:
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '<a href="' + arr[i].url + '">' + arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
myFunction(myArray);
3: Create a text file
Put the array literal in a file named myTutorials.txt:
[
{
"display": "JavaScript Tutorial",
"url": "http://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "http://www.w3schools.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "http://www.w3schools.com/css/default.asp"
}
]
4: Read the text file with an XMLHttpRequest
Write an XMLHttpRequest to read the text file, and use myFunction() to display the array:
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
<div id="id01"></div>
<script>
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i<arr.length; i++) {
out += '<a href="' + arr[i].url + '">' + arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
</script>
<script src="myTutorials.js"></script>
var myArray = [
{
"display": "JavaScript Tutorial",
"url": "http://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "http://www.w3schools.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "http://www.w3schools.com/css/default.asp"
}
]
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '<a href="' + arr[i].url + '">' + arr[i].display +
'</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
myFunction([
{
"display": "JavaScript Tutorial",
"url": "http://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "http://www.w3schools.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "http://www.w3schools.com/css/default.asp"
}
]);
myFunction([
{
"display": "JavaScript Tutorial",
"url": "http://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "http://www.w3schools.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "http://www.w3schools.com/css/default.asp""
}
]);
<!DOCTYPE html>
<html>
<body>
<h1>Customers</h1>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://www.w3schools.com/website/customers_mysql.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Name +
"</td><td>" +
arr[i].City +
"</td><td>" +
arr[i].Country +
"</td></tr>";
}
out += "</table>"
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("myServer", "myUser", "myPassword", "Northwind");
$result = $conn->query("SELECT CompanyName, City, Country FROM Customers");
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"Name":"' . $rs["CompanyName"] . '",';
$outp .= '"City":"' . $rs["City"] . '",';
$outp .= '"Country":"'. $rs["Country"] . '"}';
}
$outp .="]";
$conn->close();
echo($outp);
?>
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
border-bottom:3px solid #cc9900;
color: #996600;
font-size: 30px;
}
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd){
background-color: #f1f1f1;
}
table tr:nth-child(even){
background-color: #ffffff;
}
</style>
</head>
<body>
<h1>Customers</h1>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://www.w3schools.com/website/customers_mysql.php";
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET",url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>"+
arr[i].Name+
"</td><td>"+
arr[i].City+
"</td><td>"+
arr[i].Country+
"</td></tr>";
}
out += "</table>"
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>

More Related Content

What's hot (20)

Introduction to JSON & AJAX
Introduction to JSON & AJAX
Collaboration Technologies
 
Json
Json
Raphael Wanjiku
 
Json
Json
elliando dias
 
J s-o-n-120219575328402-3
J s-o-n-120219575328402-3
Ramamohan Chokkam
 
Intro to JSON
Intro to JSON
George McKinney
 
Json tutorial, a beguiner guide
Json tutorial, a beguiner guide
Rafael Montesinos Muñoz
 
JSON
JSON
Yoga Raja
 
Java script
Java script
Yoga Raja
 
Javascript2839
Javascript2839
Ramamohan Chokkam
 
java script json
java script json
chauhankapil
 
Json the-x-in-ajax1588
Json the-x-in-ajax1588
Ramamohan Chokkam
 
Ajax
Ajax
Manav Prasad
 
Jsonsaga 100605143125-phpapp02
Jsonsaga 100605143125-phpapp02
Ramamohan Chokkam
 
Json
Json
soumya
 
Json
Json
Prabhat gangwar
 
Json
Json
baabtra.com - No. 1 supplier of quality freshers
 
JSON Processing in the Database using PostgreSQL 9.4 :: Data Wranglers DC :: ...
JSON Processing in the Database using PostgreSQL 9.4 :: Data Wranglers DC :: ...
Ryan B Harvey, CSDP, CSM
 
Json
Json
Anderson Oliveira
 
JSON Injection
JSON Injection
n|u - The Open Security Community
 
ActiveRecord vs Mongoid
ActiveRecord vs Mongoid
Ivan Nemytchenko
 

Viewers also liked (6)

Ajax Tutorial
Ajax Tutorial
oscon2007
 
Open Ldap Integration and Configuration with Lifray 6.2
Open Ldap Integration and Configuration with Lifray 6.2
Vinaykumar Hebballi
 
Json vs Gson vs Jackson
Json vs Gson vs Jackson
Vinaykumar Hebballi
 
Ajax Ppt 1
Ajax Ppt 1
JayaPrakash.m
 
Introduction to ajax
Introduction to ajax
Nir Elbaz
 
Ajax ppt - 32 slides
Ajax ppt - 32 slides
Smithss25
 
Ajax Tutorial
Ajax Tutorial
oscon2007
 
Open Ldap Integration and Configuration with Lifray 6.2
Open Ldap Integration and Configuration with Lifray 6.2
Vinaykumar Hebballi
 
Introduction to ajax
Introduction to ajax
Nir Elbaz
 
Ajax ppt - 32 slides
Ajax ppt - 32 slides
Smithss25
 
Ad

Similar to JSON(JavaScript Object Notation) (20)

Json
Json
Steve Fort
 
CS8651 IP Unit 2 pdf regulation -2017 anna university
CS8651 IP Unit 2 pdf regulation -2017 anna university
amrashbhanuabdul
 
Internet and Web Technology (CLASS-8) [jQuery and JSON] | NIC/NIELIT Web Tech...
Internet and Web Technology (CLASS-8) [jQuery and JSON] | NIC/NIELIT Web Tech...
Ayes Chinmay
 
JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)
Skillwise Group
 
Json
Json
krishnapriya Tadepalli
 
Introduction to JSON and Building Youtube, Twitter and Wikipedia Web Apps
Introduction to JSON and Building Youtube, Twitter and Wikipedia Web Apps
Raghavendra Nayak
 
JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2
Laurence Svekis ✔
 
Json tutorial for beginners phptpoint
Json tutorial for beginners phptpoint
phptpoint
 
JSON & AJAX.pptx
JSON & AJAX.pptx
dyumna2
 
Java script
Java script
Adrian Caetano
 
JSON Presentation.pptx JSON Presentation.pptx
JSON Presentation.pptx JSON Presentation.pptx
trwdcn
 
JavaScript Object Notation (JSON)
JavaScript Object Notation (JSON)
BOSS Webtech
 
Json Tutorial
Json Tutorial
Napendra Singh
 
BITM3730Week8.pptx
BITM3730Week8.pptx
MattMarino13
 
json.pptx
json.pptx
Anum Zehra
 
JSON: The Basics
JSON: The Basics
Jeff Fox
 
JavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talk
Thomas Kjeldahl Nilsson
 
module 2.pptx for full stack mobile development application on backend applic...
module 2.pptx for full stack mobile development application on backend applic...
HemaSenthil5
 
JavaScript Needn't Hurt!
JavaScript Needn't Hurt!
Thomas Kjeldahl Nilsson
 
JavaScript and jQuery Fundamentals
JavaScript and jQuery Fundamentals
BG Java EE Course
 
CS8651 IP Unit 2 pdf regulation -2017 anna university
CS8651 IP Unit 2 pdf regulation -2017 anna university
amrashbhanuabdul
 
Internet and Web Technology (CLASS-8) [jQuery and JSON] | NIC/NIELIT Web Tech...
Internet and Web Technology (CLASS-8) [jQuery and JSON] | NIC/NIELIT Web Tech...
Ayes Chinmay
 
JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)
Skillwise Group
 
Introduction to JSON and Building Youtube, Twitter and Wikipedia Web Apps
Introduction to JSON and Building Youtube, Twitter and Wikipedia Web Apps
Raghavendra Nayak
 
Json tutorial for beginners phptpoint
Json tutorial for beginners phptpoint
phptpoint
 
JSON & AJAX.pptx
JSON & AJAX.pptx
dyumna2
 
JSON Presentation.pptx JSON Presentation.pptx
JSON Presentation.pptx JSON Presentation.pptx
trwdcn
 
JavaScript Object Notation (JSON)
JavaScript Object Notation (JSON)
BOSS Webtech
 
BITM3730Week8.pptx
BITM3730Week8.pptx
MattMarino13
 
JSON: The Basics
JSON: The Basics
Jeff Fox
 
module 2.pptx for full stack mobile development application on backend applic...
module 2.pptx for full stack mobile development application on backend applic...
HemaSenthil5
 
JavaScript and jQuery Fundamentals
JavaScript and jQuery Fundamentals
BG Java EE Course
 
Ad

More from Raghu nath (20)

Mongo db
Mongo db
Raghu nath
 
Ftp (file transfer protocol)
Ftp (file transfer protocol)
Raghu nath
 
MS WORD 2013
MS WORD 2013
Raghu nath
 
Msword
Msword
Raghu nath
 
Ms word
Ms word
Raghu nath
 
Javascript part1
Javascript part1
Raghu nath
 
Regular expressions
Regular expressions
Raghu nath
 
Selection sort
Selection sort
Raghu nath
 
Binary search
Binary search
Raghu nath
 
Stemming algorithms
Stemming algorithms
Raghu nath
 
Step by step guide to install dhcp role
Step by step guide to install dhcp role
Raghu nath
 
Network essentials chapter 4
Network essentials chapter 4
Raghu nath
 
Network essentials chapter 3
Network essentials chapter 3
Raghu nath
 
Network essentials chapter 2
Network essentials chapter 2
Raghu nath
 
Network essentials - chapter 1
Network essentials - chapter 1
Raghu nath
 
Python chapter 2
Python chapter 2
Raghu nath
 
python chapter 1
python chapter 1
Raghu nath
 
Linux Shell Scripting
Linux Shell Scripting
Raghu nath
 
Perl
Perl
Raghu nath
 
Adv excel® 2013
Adv excel® 2013
Raghu nath
 
Ftp (file transfer protocol)
Ftp (file transfer protocol)
Raghu nath
 
Javascript part1
Javascript part1
Raghu nath
 
Regular expressions
Regular expressions
Raghu nath
 
Selection sort
Selection sort
Raghu nath
 
Binary search
Binary search
Raghu nath
 
Stemming algorithms
Stemming algorithms
Raghu nath
 
Step by step guide to install dhcp role
Step by step guide to install dhcp role
Raghu nath
 
Network essentials chapter 4
Network essentials chapter 4
Raghu nath
 
Network essentials chapter 3
Network essentials chapter 3
Raghu nath
 
Network essentials chapter 2
Network essentials chapter 2
Raghu nath
 
Network essentials - chapter 1
Network essentials - chapter 1
Raghu nath
 
Python chapter 2
Python chapter 2
Raghu nath
 
python chapter 1
python chapter 1
Raghu nath
 
Linux Shell Scripting
Linux Shell Scripting
Raghu nath
 
Adv excel® 2013
Adv excel® 2013
Raghu nath
 

Recently uploaded (20)

Vikas Bansal Himachal Pradesh: A Visionary Transforming Himachal’s Educationa...
Vikas Bansal Himachal Pradesh: A Visionary Transforming Himachal’s Educationa...
Himalayan Group of Professional Institutions (HGPI)
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
Sustainable Innovation with Immersive Learning
Sustainable Innovation with Immersive Learning
Leonel Morgado
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
How to Manage Multi Language for Invoice in Odoo 18
How to Manage Multi Language for Invoice in Odoo 18
Celine George
 
BINARY files CSV files JSON files with example.pptx
BINARY files CSV files JSON files with example.pptx
Ramakrishna Reddy Bijjam
 
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
Sourav Kr Podder
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
Arshad Shaikh
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
Chalukyas of Gujrat, Solanki Dynasty NEP.pptx
Chalukyas of Gujrat, Solanki Dynasty NEP.pptx
Dr. Ravi Shankar Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
How to Manage Inventory Movement in Odoo 18 POS
How to Manage Inventory Movement in Odoo 18 POS
Celine George
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
The Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdf
dennisongomezk
 
Introduction to Generative AI and Copilot.pdf
Introduction to Generative AI and Copilot.pdf
TechSoup
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
Sustainable Innovation with Immersive Learning
Sustainable Innovation with Immersive Learning
Leonel Morgado
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
How to Manage Multi Language for Invoice in Odoo 18
How to Manage Multi Language for Invoice in Odoo 18
Celine George
 
BINARY files CSV files JSON files with example.pptx
BINARY files CSV files JSON files with example.pptx
Ramakrishna Reddy Bijjam
 
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
Sourav Kr Podder
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
Arshad Shaikh
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
How to Manage Inventory Movement in Odoo 18 POS
How to Manage Inventory Movement in Odoo 18 POS
Celine George
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
The Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdf
dennisongomezk
 
Introduction to Generative AI and Copilot.pdf
Introduction to Generative AI and Copilot.pdf
TechSoup
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 

JSON(JavaScript Object Notation)

  • 2. JSON: JavaScript Object Notation. JSON is a syntax for storing and exchanging data. JSON is an easier-to-use alternative to XML.
  • 3. JSON Example {"employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ]}
  • 4. The following XML example also defines an employees object with 3 employee records: <employees> <employee> <firstName>John</firstName> <lastName>Doe</lastName> </employee> <employee> <firstName>Anna</firstName> <lastName>Smith</lastName> </employee> <employee> <firstName>Peter</firstName> <lastName>Jones</lastName> </employee> </employees>
  • 5. JSON - Evaluates to JavaScript Objects The JSON format is syntactically identical to the code for creating JavaScript objects. Because of this similarity, instead of using a parser (like XML does), a JavaScript program can use standard JavaScript functions to convert JSON data into native JavaScript objects.
  • 6. JSON Example <!DOCTYPE html> <html> <body> <h2>JSON Object Creation in JavaScript</h2> <p id="demo"></p> <script> var text = '{"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}'; var obj = JSON.parse(text); document.getElementById("demo").innerHTML = obj.name + "<br>" + obj.street + "<br>" + obj.phone; </script> </body> </html>
  • 7. JSON Syntax Rules JSON syntax is derived from JavaScript object notation syntax: Data is in name/value pairs Data is separated by commas Curly braces hold objects Square brackets hold arrays
  • 8. JSON Data - A Name and a Value JSON data is written as name/value pairs. A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value:
  • 10. JSON Objects JSON objects are written inside curly braces. Just like JavaScript, JSON objects can contain multiple name/values pairs:
  • 12. JSON Arrays JSON arrays are written inside square brackets. Just like JavaScript, a JSON array can contain multiple objects:
  • 14. In the example above, the object "employees" is an array containing three objects. Each object is a record of a person (with a first name and a last name).
  • 15. JSON Uses JavaScript Syntax Because JSON syntax is derived from JavaScript object notation, very little extra software is needed to work with JSON within JavaScript. With JavaScript you can create an array of objects and assign data to it, like this:
  • 16. var employees = [ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter","lastName": "Jones"} ];
  • 17. employees[0].firstName + " " + employees[0].lastName;
  • 18. employees[0]["firstName"] + " " + employees[0]["lastName"];
  • 19. A common use of JSON is to read data from a web server, and display the data in a web page. For simplicity, this can be demonstrated by using a string as input (instead of a file). JSON Example - Object From String Create a JavaScript string containing JSON syntax:
  • 20. var text = '{ "employees" : [' + '{ "firstName":"John" , "lastName":"Doe" },' + '{ "firstName":"Anna" , "lastName":"Smith" },' + '{ "firstName":"Peter" , "lastName":"Jones" } ]}'; JSON syntax is a subset of JavaScript syntax. The JavaScript function JSON.parse(text) can be used to convert a JSON text into a JavaScript object:
  • 21. var obj = JSON.parse(text);
  • 23. Using eval() Older browsers without the support for the JavaScript function JSON.parse() can use the eval() function to convert a JSON text into a JavaScript object: var obj = eval ("(" + text + ")");
  • 24. JSON Http Request A common use of JSON is to read data from a web server, and display the data in a web page. This chapter will teach you, in 4 easy steps, how to read JSON data, using XMLHttp.
  • 25. <div id="id01"></div> <script> var xmlhttp = new XMLHttpRequest(); var url = "myTutorials.txt"; xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var myArr = JSON.parse(xmlhttp.responseText); myFunction(myArr); } } xmlhttp.open("GET", url, true); xmlhttp.send(); function myFunction(arr) { var out = ""; var i; for(i = 0; i < arr.length; i++) { out += '<a href="' + arr[i].url + '">' + arr[i].display + '</a><br>'; } document.getElementById("id01").innerHTML = out; } </script>
  • 26. Example Explained 1: Create an array of objects. Use an array literal to declare an array of objects. Give each object two properties: display and url. Name the array myArray:
  • 27. var myArray = [ { "display": "JavaScript Tutorial", "url": "http://www.w3schools.com/js/default.asp" }, { "display": "HTML Tutorial", "url": "http://www.w3schools.com/html/default.asp" }, { "display": "CSS Tutorial", "url": "http://www.w3schools.com/css/default.asp" } ]
  • 28. 2: Create a JavaScript function to display the array. Create a function myFunction() that loops the array objects, and display the content as HTML links:
  • 29. function myFunction(arr) { var out = ""; var i; for(i = 0; i < arr.length; i++) { out += '<a href="' + arr[i].url + '">' + arr[i].display + '</a><br>'; } document.getElementById("id01").innerHTML = out; }
  • 31. 3: Create a text file Put the array literal in a file named myTutorials.txt: [ { "display": "JavaScript Tutorial", "url": "http://www.w3schools.com/js/default.asp" }, { "display": "HTML Tutorial", "url": "http://www.w3schools.com/html/default.asp" }, { "display": "CSS Tutorial", "url": "http://www.w3schools.com/css/default.asp" } ]
  • 32. 4: Read the text file with an XMLHttpRequest Write an XMLHttpRequest to read the text file, and use myFunction() to display the array:
  • 33. var xmlhttp = new XMLHttpRequest(); var url = "myTutorials.txt"; xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var myArr = JSON.parse(xmlhttp.responseText); myFunction(myArr); } } xmlhttp.open("GET", url, true); xmlhttp.send();
  • 34. <div id="id01"></div> <script> function myFunction(arr) { var out = ""; var i; for(i = 0; i<arr.length; i++) { out += '<a href="' + arr[i].url + '">' + arr[i].display + '</a><br>'; } document.getElementById("id01").innerHTML = out; } </script> <script src="myTutorials.js"></script>
  • 35. var myArray = [ { "display": "JavaScript Tutorial", "url": "http://www.w3schools.com/js/default.asp" }, { "display": "HTML Tutorial", "url": "http://www.w3schools.com/html/default.asp" }, { "display": "CSS Tutorial", "url": "http://www.w3schools.com/css/default.asp" } ]
  • 36. function myFunction(arr) { var out = ""; var i; for(i = 0; i < arr.length; i++) { out += '<a href="' + arr[i].url + '">' + arr[i].display + '</a><br>'; } document.getElementById("id01").innerHTML = out; }
  • 37. myFunction([ { "display": "JavaScript Tutorial", "url": "http://www.w3schools.com/js/default.asp" }, { "display": "HTML Tutorial", "url": "http://www.w3schools.com/html/default.asp" }, { "display": "CSS Tutorial", "url": "http://www.w3schools.com/css/default.asp" } ]);
  • 38. myFunction([ { "display": "JavaScript Tutorial", "url": "http://www.w3schools.com/js/default.asp" }, { "display": "HTML Tutorial", "url": "http://www.w3schools.com/html/default.asp" }, { "display": "CSS Tutorial", "url": "http://www.w3schools.com/css/default.asp"" } ]);
  • 39. <!DOCTYPE html> <html> <body> <h1>Customers</h1> <div id="id01"></div> <script> var xmlhttp = new XMLHttpRequest(); var url = "http://www.w3schools.com/website/customers_mysql.php"; xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { myFunction(xmlhttp.responseText); } } xmlhttp.open("GET", url, true); xmlhttp.send(); function myFunction(response) { var arr = JSON.parse(response); var i; var out = "<table>"; for(i = 0; i < arr.length; i++) { out += "<tr><td>" + arr[i].Name + "</td><td>" + arr[i].City + "</td><td>" + arr[i].Country + "</td></tr>"; } out += "</table>" document.getElementById("id01").innerHTML = out; } </script> </body> </html>
  • 40. <?php header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8"); $conn = new mysqli("myServer", "myUser", "myPassword", "Northwind"); $result = $conn->query("SELECT CompanyName, City, Country FROM Customers"); $outp = "["; while($rs = $result->fetch_array(MYSQLI_ASSOC)) { if ($outp != "[") {$outp .= ",";} $outp .= '{"Name":"' . $rs["CompanyName"] . '",'; $outp .= '"City":"' . $rs["City"] . '",'; $outp .= '"Country":"'. $rs["Country"] . '"}'; } $outp .="]"; $conn->close(); echo($outp); ?>
  • 41. <!DOCTYPE html> <html> <head> <style> h1 { border-bottom:3px solid #cc9900; color: #996600; font-size: 30px; } table, th , td { border: 1px solid grey; border-collapse: collapse; padding: 5px; } table tr:nth-child(odd){ background-color: #f1f1f1; } table tr:nth-child(even){ background-color: #ffffff; } </style> </head> <body> <h1>Customers</h1> <div id="id01"></div> <script> var xmlhttp = new XMLHttpRequest(); var url = "http://www.w3schools.com/website/customers_mysql.php"; xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { myFunction(xmlhttp.responseText); } } xmlhttp.open("GET",url, true); xmlhttp.send(); function myFunction(response) { var arr = JSON.parse(response); var i; var out = "<table>"; for(i = 0; i < arr.length; i++) { out += "<tr><td>"+ arr[i].Name+ "</td><td>"+ arr[i].City+ "</td><td>"+ arr[i].Country+ "</td></tr>"; } out += "</table>" document.getElementById("id01").innerHTML = out; } </script> </body> </html>