SlideShare une entreprise Scribd logo
1  sur  20
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

Contenu connexe

Tendances

Tendances (20)

Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
 
Object Oriented Javascript
Object Oriented JavascriptObject Oriented Javascript
Object Oriented Javascript
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
Java script
Java scriptJava script
Java script
 
Web api
Web apiWeb api
Web api
 
javascript objects
javascript objectsjavascript objects
javascript objects
 
Mongo db
Mongo dbMongo db
Mongo db
 
What is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaWhat is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | Edureka
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arrays
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Intro to HTML and CSS basics
Intro to HTML and CSS basicsIntro to HTML and CSS basics
Intro to HTML and CSS basics
 
Javascript 101
Javascript 101Javascript 101
Javascript 101
 
Introduction to Django Rest Framework
Introduction to Django Rest FrameworkIntroduction to Django Rest Framework
Introduction to Django Rest Framework
 
JavaScript Data Types
JavaScript Data TypesJavaScript Data Types
JavaScript Data Types
 

Similaire à Json

Similaire à Json (20)

JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)
 
Json tutorial, a beguiner guide
Json tutorial, a beguiner guideJson tutorial, a beguiner guide
Json tutorial, a beguiner guide
 
Json
JsonJson
Json
 
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
 
JSON
JSONJSON
JSON
 
JSON & AJAX.pptx
JSON & AJAX.pptxJSON & AJAX.pptx
JSON & AJAX.pptx
 
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
 
AJAX
AJAXAJAX
AJAX
 
Introduction to JSON
Introduction to JSONIntroduction to JSON
Introduction to JSON
 
JSON(JavaScript Object Notation)
JSON(JavaScript Object Notation)JSON(JavaScript Object Notation)
JSON(JavaScript Object Notation)
 
Hands on JSON
Hands on JSONHands on JSON
Hands on JSON
 
J s-o-n-120219575328402-3
J s-o-n-120219575328402-3J s-o-n-120219575328402-3
J s-o-n-120219575328402-3
 
Json
JsonJson
Json
 
Json
JsonJson
Json
 
Json the-x-in-ajax1588
Json the-x-in-ajax1588Json the-x-in-ajax1588
Json the-x-in-ajax1588
 
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
 
java script json
java script jsonjava script json
java script json
 
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
 
Advanced Json
Advanced JsonAdvanced Json
Advanced Json
 
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
 

Dernier

SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 

Dernier (20)

SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 

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