SlideShare a Scribd company logo
JSON
(JavaScript Object Notation)
infobizzs.com
What is JSON?
• JSON stands for JavaScript Object Notation
• JSON is a lightweight data-interchange format
• JSON is language independent *
• JSON is "self-describing" and easy to understand
• JSON is a syntax for storing and exchanging data.
• JSON is an easier-to-use alternative to XML.
infobizzs.com
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> infobizzs.com
Output
infobizzs.com
 Much Like XML Because
• Both JSON and XML is "self describing" (human readable)
• Both JSON and XML is hierarchichal (values within values)
• Both JSON and XML can be parsed and used by lots of programming languages
• Both JSON and XML can be fetched with an XMLHttpRequest
 Much Unlike XML Because
• JSON doesn't use end tag
• JSON is shorter
• JSON is quicker to read and write
• JSON can use arrays
• The biggest difference is:
XML has to be parsed with an XML parser, JSON can be parsed by a standard JavaScript function.
infobizzs.com
Why JSON?
For AJAX applications, JSON is faster and easier than XML:
• Using XML
• Fetch an XML document
• Use the XML DOM to loop through the document
• Extract values and store in variables
• Using JSON
• Fetch a JSON string
• JSON.Parse the JSON string
infobizzs.com
JSON Syntax
The JSON syntax is a subset of the JavaScript syntax.
• 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
infobizzs.com
JSON Data - A Name and aValue
• 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"
• JSONValues
• JSON values can be:
• A number (integer or floating point)
• A string (in double quotes)
• A Boolean (true or false)
• An array (in square brackets)
• An object (in curly braces)
• null
infobizzs.com
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"}
]
infobizzs.com
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"}
];
infobizzs.com
JSON HowTo
• 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" } ]}';
infobizzs.com
• 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);
Use the new JavaScript object in your page:
• Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>
infobizzs.com
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.
• This example reads a menu from myTutorials.txt, and displays the menu in a web page:
<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);
}
}
infobizzs.com
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>
infobizzs.com
Output
infobizzs.com
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:
myArray
var myArray = [
{
"display": "JavaScriptTutorial",
"url": "http://www.w3schools.com/js/default.asp"
},
{
"display": "HTMLTutorial",
"url": "http://www.w3schools.com/html/default.asp"
},
{
"display": "CSSTutorial",
"url": "http://www.w3schools.com/css/default.asp"
}
]
infobizzs.com
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:
myFunction()
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;
}
infobizzs.com
3: Create a text file
• Put the array literal in a file named myTutorials.txt:
myTutorials.txt
[
{
"display": "JavaScriptTutorial",
"url": "http://www.w3schools.com/js/default.asp"
},
{
"display": "HTMLTutorial",
"url": "http://www.w3schools.com/html/default.asp"
},
{
"display": "CSSTutorial",
"url": "http://www.w3schools.com/css/default.asp"
}
]
infobizzs.com
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();
infobizzs.com
Output
infobizzs.com
Ad

More Related Content

What's hot (20)

Json
JsonJson
Json
Sabarinath Gnanasekar
 
JavaScript Object Notation (JSON)
JavaScript Object Notation (JSON)JavaScript Object Notation (JSON)
JavaScript Object Notation (JSON)
BOSS Webtech
 
Dom(document object model)
Dom(document object model)Dom(document object model)
Dom(document object model)
Partnered Health
 
ASP.NET Basics
ASP.NET Basics ASP.NET Basics
ASP.NET Basics
baabtra.com - No. 1 supplier of quality freshers
 
Json Tutorial
Json TutorialJson Tutorial
Json Tutorial
Napendra Singh
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
yht4ever
 
Json
JsonJson
Json
krishnapriya Tadepalli
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
Arulmurugan Rajaraman
 
HTTP Request and Response Structure
HTTP Request and Response StructureHTTP Request and Response Structure
HTTP Request and Response Structure
BhagyashreeGajera1
 
Statements and Conditions in PHP
Statements and Conditions in PHPStatements and Conditions in PHP
Statements and Conditions in PHP
Maruf Abdullah (Rion)
 
Introduction to JSON
Introduction to JSONIntroduction to JSON
Introduction to JSON
Kanda Runapongsa Saikaew
 
Javascript
JavascriptJavascript
Javascript
Sun Technlogies
 
Control Structures In Php 2
Control Structures In Php 2Control Structures In Php 2
Control Structures In Php 2
Digital Insights - Digital Marketing Agency
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
shreesenthil
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScript
ShahDhruv21
 
Java script
Java scriptJava script
Java script
Shyam Khant
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)
WebStackAcademy
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
Amit Tyagi
 
javaScript.ppt
javaScript.pptjavaScript.ppt
javaScript.ppt
sentayehu
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 

Similar to Json (20)

JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)
Skillwise Group
 
Json tutorial, a beguiner guide
Json tutorial, a beguiner guideJson tutorial, a beguiner guide
Json tutorial, a beguiner guide
Rafael Montesinos Muñoz
 
Json
JsonJson
Json
Anand Kumar Rajana
 
Basics of JSON (JavaScript Object Notation) with examples
Basics of JSON (JavaScript Object Notation) with examplesBasics of JSON (JavaScript Object Notation) with examples
Basics of JSON (JavaScript Object Notation) with examples
Sanjeev Kumar Jaiswal
 
JSON
JSONJSON
JSON
Yoga Raja
 
JSON & AJAX.pptx
JSON & AJAX.pptxJSON & AJAX.pptx
JSON & AJAX.pptx
dyumna2
 
A Higher-Order Data Flow Model for Heterogeneous Big Data
A Higher-Order Data Flow Model for Heterogeneous Big DataA Higher-Order Data Flow Model for Heterogeneous Big Data
A Higher-Order Data Flow Model for Heterogeneous Big Data
Simon Price
 
AJAX
AJAXAJAX
AJAX
Jussi Pohjolainen
 
JSON(JavaScript Object Notation)
JSON(JavaScript Object Notation)JSON(JavaScript Object Notation)
JSON(JavaScript Object Notation)
Raghu nath
 
Hands on JSON
Hands on JSONHands on JSON
Hands on JSON
Octavian Nadolu
 
J s-o-n-120219575328402-3
J s-o-n-120219575328402-3J s-o-n-120219575328402-3
J s-o-n-120219575328402-3
Ramamohan Chokkam
 
Json
JsonJson
Json
soumya
 
Json
JsonJson
Json
Anderson Oliveira
 
Json the-x-in-ajax1588
Json the-x-in-ajax1588Json the-x-in-ajax1588
Json the-x-in-ajax1588
Ramamohan Chokkam
 
Json at work overview and ecosystem-v2.0
Json at work   overview and ecosystem-v2.0Json at work   overview and ecosystem-v2.0
Json at work overview and ecosystem-v2.0
Boulder Java User's Group
 
java script json
java script jsonjava script json
java script json
chauhankapil
 
JSON Fuzzing: New approach to old problems
JSON Fuzzing: New  approach to old problemsJSON Fuzzing: New  approach to old problems
JSON Fuzzing: New approach to old problems
titanlambda
 
Advanced Json
Advanced JsonAdvanced Json
Advanced Json
guestfd7d7c
 
json.ppt download for free for college project
json.ppt download for free for college projectjson.ppt download for free for college project
json.ppt download for free for college project
AmitSharma397241
 
Json
JsonJson
Json
Raphael Wanjiku
 
Ad

Recently uploaded (20)

SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Ad

Json

  • 2. What is JSON? • JSON stands for JavaScript Object Notation • JSON is a lightweight data-interchange format • JSON is language independent * • JSON is "self-describing" and easy to understand • JSON is a syntax for storing and exchanging data. • JSON is an easier-to-use alternative to XML. infobizzs.com
  • 3. 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> infobizzs.com
  • 5.  Much Like XML Because • Both JSON and XML is "self describing" (human readable) • Both JSON and XML is hierarchichal (values within values) • Both JSON and XML can be parsed and used by lots of programming languages • Both JSON and XML can be fetched with an XMLHttpRequest  Much Unlike XML Because • JSON doesn't use end tag • JSON is shorter • JSON is quicker to read and write • JSON can use arrays • The biggest difference is: XML has to be parsed with an XML parser, JSON can be parsed by a standard JavaScript function. infobizzs.com
  • 6. Why JSON? For AJAX applications, JSON is faster and easier than XML: • Using XML • Fetch an XML document • Use the XML DOM to loop through the document • Extract values and store in variables • Using JSON • Fetch a JSON string • JSON.Parse the JSON string infobizzs.com
  • 7. JSON Syntax The JSON syntax is a subset of the JavaScript syntax. • 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 infobizzs.com
  • 8. JSON Data - A Name and aValue • 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" • JSONValues • JSON values can be: • A number (integer or floating point) • A string (in double quotes) • A Boolean (true or false) • An array (in square brackets) • An object (in curly braces) • null infobizzs.com
  • 9. 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"} ] infobizzs.com
  • 10. 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"} ]; infobizzs.com
  • 11. JSON HowTo • 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" } ]}'; infobizzs.com
  • 12. • 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); Use the new JavaScript object in your page: • Example <p id="demo"></p> <script> document.getElementById("demo").innerHTML = obj.employees[1].firstName + " " + obj.employees[1].lastName; </script> infobizzs.com
  • 13. 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. • This example reads a menu from myTutorials.txt, and displays the menu in a web page: <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); } } infobizzs.com
  • 14. 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> infobizzs.com
  • 16. 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: myArray var myArray = [ { "display": "JavaScriptTutorial", "url": "http://www.w3schools.com/js/default.asp" }, { "display": "HTMLTutorial", "url": "http://www.w3schools.com/html/default.asp" }, { "display": "CSSTutorial", "url": "http://www.w3schools.com/css/default.asp" } ] infobizzs.com
  • 17. 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: myFunction() 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; } infobizzs.com
  • 18. 3: Create a text file • Put the array literal in a file named myTutorials.txt: myTutorials.txt [ { "display": "JavaScriptTutorial", "url": "http://www.w3schools.com/js/default.asp" }, { "display": "HTMLTutorial", "url": "http://www.w3schools.com/html/default.asp" }, { "display": "CSSTutorial", "url": "http://www.w3schools.com/css/default.asp" } ] infobizzs.com
  • 19. 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(); infobizzs.com