SlideShare a Scribd company logo
JSON
C.A.Yogaraja
Department of Computer Science and Engineering
Ramco Institute of Technonlogy
Introduction
• JSON: JavaScript Object Notation.
• JSON is a syntax for storing and exchanging data.
• JSON is text, written with JavaScript object
notation.
• JSON is a lightweight data-interchange format
• JSON is "self-describing" and easy to understand
• JSON is language independent
• JSON uses JavaScript syntax, but the JSON format
is text only
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
• Eg: { “firstname":"John“, “age”:”20”,
“skill”:[“C”,”C++”], "sale":true, "middlename":null }
JSON Values
• In JSON, values must be one of the following
data types:
– a string
– a number
– an object (JSON object)
– an array
– a boolean
– null
JSON Objects
• Looping an Object
– for-in loop
• myObj = { "name":"John", "age":30, "car":null };
for (x in myObj)
{
document.getElementById("demo").innerHTML += x;
}
– name
age
car
JSON Objects
• Nested JSON Objects
– myObj = {"name":"John", "age":30, "cars":
{
"car1":"Ford",
"car2":"BMW",
"car3":"Fiat"
}
}
Accessing Values: x = myObj.cars.car2;
Modify Values: myObj.cars.car2 = "Mercedes";
Deleting: delete myObj.cars.car2;
JSON Arrays
• myObj={"name":"John","age":30,
"cars":[ "Ford", "BMW", "Fiat" ]
}
• Accessing:
– x = myObj.cars[0];
• Accessing Via Loop:
– for (i in myObj.cars) {
x += myObj.cars[i];
}
Exchanging Data
• When exchanging data between a browser and a
server, the data can only be text.
• JSON is text, and we can convert any JavaScript
object into JSON, and send JSON to the server.
• We can also convert any JSON received from the
server into JavaScript objects.
• This way we can work with the data as JavaScript
objects, with no complicated parsing and
translations.
Exchanging Data-Sending Data
• A common use of JSON is to exchange data to/from a web
server.
• When sending data to a web server, the data has to be a
string.
• Convert a JavaScript object into a string
with JSON.stringify().
var myObj = {name: "John", age: 31, city: "New York"};
var myJSON = JSON.stringify(myObj);
document.getElementById("demo").innerHTML = myJSON;
Exchanging Data-Sending Data
Exceptions
• Stringify Dates
– In JSON, date objects are not allowed. The JSON.stringify() function
will convert any dates into strings.
– var obj = { name: "John", today: new Date()};
– var myJSON = JSON.stringify(obj);
– document.getElementById("demo").innerHTML = myJSON;
{"name":"John","today":"2020-01-23T04:46:38.759Z"}
Exchanging Data-Sending Data
Exceptions
• Stringify Functions
– In JSON, functions are not allowed as object values.
– The JSON.stringify() function will remove any functions from a
JavaScript object, both the key and the value:
– var obj = { name: "John", age: function () {return 30;}};
– var myJSON = JSON.stringify(obj);
– document.getElementById("demo").innerHTML = myJSON;
{"name":"John"}
Exchanging Data-Receiving Data
• 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.
var myJSON = '{"name":"John", "age":31, "city":"New York"}';
var myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj.name;
Storing Data
• When storing data, the data has to be a
certain format, and regardless of where you
choose to store it, text is always one of the
legal formats.
Storing Data
// Storing data:
myObj = {name: "John", age: 31, city: "New York"};
myJSON = JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);
// Retrieving data:
text = localStorage.getItem("testJSON");
obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.name;
Function Files
• A common use of JSON is to read data from a
web server, and display the data in a web
page.
– 1: Create an array of objects.
– 2: Create a JavaScript function to display the
array.
– 3: Use an array literal as the argument (instead of
the array variable):
– 4: Put the function in an external js file
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": "https://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "https://www.w3schools.com/html/default.asp"
}
]
2: Create a JavaScript function to
display the array
• 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;
}
3: Use an array literal as the argument
(instead of the array variable)
• myFunction([
{
"display": "JavaScript Tutorial",
"url": "https://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "https://www.w3schools.com/html/default.asp"
}
]);
4: Put the function in an external js
file
• Put the function in a file named Tutorials.js:
– Add the external script to your page
– <script src="Tutorials.js"></script>
JSON HTTP Request-XMLHttpRequest()
• A common use of JSON is to read data from a
web server, and display the data in a web
page.
• JSON is most commonly used in
asynchronous HTTP requests. This is where an
application pulls data from another
application via an HTTP request on the web
Steps for performing HttpRequest
• 1: Create an array of objects.
• 2: Create a JavaScript function to display the
array.
• 3: Create a text file
• 4: Read the text file with an XMLHttpRequest
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": "https://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "https://www.w3schools.com/html/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;
}
• Call myFunction() with myArray as argument:
• myFunction(myArray);
3: Create a text file
• Put the array literal in a file
named myTutorials.txt:
[
{
"display": "JavaScript Tutorial",
"url": "https://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "https://www.w3schools.com/html/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.open("GET", url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
XMLHttpRequest object
• Update a web page without reloading the
page
• Request data from a server - after the page
has loaded
• Receive data from a server - after the page
has loaded
• Send data to a server - in the background
Creating an XMLHttpRequest Object
• var xhttp = new XMLHttpRequest();
onreadystatechange Event
• The readyState property holds the status of the
XMLHttpRequest.
• The onreadystatechange event is triggered every
time the readyState changes.
• During a server request, the readyState changes
from 0 to 4:
• 0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
onreadystatechange Event
• In the onreadystatechange property, specify a
function to be executed when the readyState
changes:
– xhttp.onreadystatechange = function()
• When readyState is 4 and status is 200, the
response is ready:
– if (this.readyState == 4 && this.status == 200)
XMLHttpRequest Properties and
Methods
Method Description
new XMLHttpRequest() Creates a new XMLHttpRequest object
open(method, url, async) Specifies the type of request
method: the type of request: GET or
POST
url: the file location
async: true (asynchronous) or false
(synchronous)
send() Sends a request to the server (used for
GET)
send(string) Sends a request string to the server
(used for POST)
XMLHttpRequest Properties and
Methods
Method Description
onreadystatechange A function to be called when the readyState
property changes
readyState 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
status 200: OK
404: Page not found
responseText The response data as a string
responseXML The response data as XML data

More Related Content

What's hot

Json
JsonJson
Java Script Object Notation (JSON)
Java Script Object Notation (JSON)Java Script Object Notation (JSON)
Java Script Object Notation (JSON)
Adnan Sohail
 
Cordova training : Day 4 - Advanced Javascript
Cordova training : Day 4 - Advanced JavascriptCordova training : Day 4 - Advanced Javascript
Cordova training : Day 4 - Advanced Javascript
Binu Paul
 
Mail OnLine Android Application at DroidCon - Turin - Italy
Mail OnLine Android Application at DroidCon - Turin - ItalyMail OnLine Android Application at DroidCon - Turin - Italy
Mail OnLine Android Application at DroidCon - Turin - Italy
Yahoo
 
JSON(JavaScript Object Notation)
JSON(JavaScript Object Notation)JSON(JavaScript Object Notation)
JSON(JavaScript Object Notation)Raghu nath
 
Json
JsonJson
Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Ramamohan Chokkam
 
java API for XML DOM
java API for XML DOMjava API for XML DOM
java API for XML DOMSurinder Kaur
 
Xml parsers
Xml parsersXml parsers
Xml parsers
Manav Prasad
 
Spring data presentation
Spring data presentationSpring data presentation
Spring data presentation
Oleksii Usyk
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
Jeevesh Pandey
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
Divakar Gu
 
An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring Data
Oliver Gierke
 
Getting started with MongoDB and Scala - Open Source Bridge 2012
Getting started with MongoDB and Scala - Open Source Bridge 2012Getting started with MongoDB and Scala - Open Source Bridge 2012
Getting started with MongoDB and Scala - Open Source Bridge 2012
sullis
 
JAXP
JAXPJAXP
JSON
JSONJSON
Advanced java practical semester 6_computer science
Advanced java practical semester 6_computer scienceAdvanced java practical semester 6_computer science
Advanced java practical semester 6_computer science
Niraj Bharambe
 

What's hot (20)

Json
JsonJson
Json
 
Java Script Object Notation (JSON)
Java Script Object Notation (JSON)Java Script Object Notation (JSON)
Java Script Object Notation (JSON)
 
JSON
JSONJSON
JSON
 
Cordova training : Day 4 - Advanced Javascript
Cordova training : Day 4 - Advanced JavascriptCordova training : Day 4 - Advanced Javascript
Cordova training : Day 4 - Advanced Javascript
 
Mail OnLine Android Application at DroidCon - Turin - Italy
Mail OnLine Android Application at DroidCon - Turin - ItalyMail OnLine Android Application at DroidCon - Turin - Italy
Mail OnLine Android Application at DroidCon - Turin - Italy
 
JSON(JavaScript Object Notation)
JSON(JavaScript Object Notation)JSON(JavaScript Object Notation)
JSON(JavaScript Object Notation)
 
Json
JsonJson
Json
 
Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268
 
Simple Data Binding
Simple Data BindingSimple Data Binding
Simple Data Binding
 
java API for XML DOM
java API for XML DOMjava API for XML DOM
java API for XML DOM
 
Xml parsers
Xml parsersXml parsers
Xml parsers
 
Spring data presentation
Spring data presentationSpring data presentation
Spring data presentation
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring Data
 
J2EE jsp_03
J2EE jsp_03J2EE jsp_03
J2EE jsp_03
 
Getting started with MongoDB and Scala - Open Source Bridge 2012
Getting started with MongoDB and Scala - Open Source Bridge 2012Getting started with MongoDB and Scala - Open Source Bridge 2012
Getting started with MongoDB and Scala - Open Source Bridge 2012
 
JAXP
JAXPJAXP
JAXP
 
JSON
JSONJSON
JSON
 
Advanced java practical semester 6_computer science
Advanced java practical semester 6_computer scienceAdvanced java practical semester 6_computer science
Advanced java practical semester 6_computer science
 

Similar to JSON

Web technologies-course 10.pptx
Web technologies-course 10.pptxWeb technologies-course 10.pptx
Web technologies-course 10.pptx
Stefan Oprea
 
BITM3730Week8.pptx
BITM3730Week8.pptxBITM3730Week8.pptx
BITM3730Week8.pptx
MattMarino13
 
Json
JsonJson
Ajaxtechnicalworkshopshortversion 1224845432835700-8
Ajaxtechnicalworkshopshortversion 1224845432835700-8Ajaxtechnicalworkshopshortversion 1224845432835700-8
Ajaxtechnicalworkshopshortversion 1224845432835700-8
anuradha raheja
 
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
 
Introduction to JSON
Introduction to JSONIntroduction to JSON
Introduction to JSON
Kanda Runapongsa Saikaew
 
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 problemstitanlambda
 
Unit-2.pptx
Unit-2.pptxUnit-2.pptx
Unit-2.pptx
AnujSood25
 
Json tutorial, a beguiner guide
Json tutorial, a beguiner guideJson tutorial, a beguiner guide
Json tutorial, a beguiner guide
Rafael Montesinos Muñoz
 
Json - ideal for data interchange
Json - ideal for data interchangeJson - ideal for data interchange
Json - ideal for data interchange
Christoph Santschi
 
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-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)
Skillwise Group
 
module 2.pptx for full stack mobile development application on backend applic...
module 2.pptx for full stack mobile development application on backend applic...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
 
JSON Processing and mule
JSON Processing and muleJSON Processing and mule
JSON Processing and mule
Santhosh Gowd
 
Java script
Java scriptJava script
Java script
vishal choudhary
 
JSON & AJAX.pptx
JSON & AJAX.pptxJSON & AJAX.pptx
JSON & AJAX.pptx
dyumna2
 

Similar to JSON (20)

Json
JsonJson
Json
 
Web technologies-course 10.pptx
Web technologies-course 10.pptxWeb technologies-course 10.pptx
Web technologies-course 10.pptx
 
BITM3730Week8.pptx
BITM3730Week8.pptxBITM3730Week8.pptx
BITM3730Week8.pptx
 
Json
JsonJson
Json
 
AJAX
AJAXAJAX
AJAX
 
Ajaxtechnicalworkshopshortversion 1224845432835700-8
Ajaxtechnicalworkshopshortversion 1224845432835700-8Ajaxtechnicalworkshopshortversion 1224845432835700-8
Ajaxtechnicalworkshopshortversion 1224845432835700-8
 
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
 
Introduction to JSON
Introduction to JSONIntroduction to JSON
Introduction to 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
 
Unit-2.pptx
Unit-2.pptxUnit-2.pptx
Unit-2.pptx
 
Json tutorial, a beguiner guide
Json tutorial, a beguiner guideJson tutorial, a beguiner guide
Json tutorial, a beguiner guide
 
Json - ideal for data interchange
Json - ideal for data interchangeJson - ideal for data interchange
Json - ideal for data interchange
 
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
 
JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)
 
Json the-x-in-ajax1588
Json the-x-in-ajax1588Json the-x-in-ajax1588
Json the-x-in-ajax1588
 
module 2.pptx for full stack mobile development application on backend applic...
module 2.pptx for full stack mobile development application on backend applic...module 2.pptx for full stack mobile development application on backend applic...
module 2.pptx for full stack mobile development application on backend applic...
 
JSON Processing and mule
JSON Processing and muleJSON Processing and mule
JSON Processing and mule
 
Java script
Java scriptJava script
Java script
 
JSON & AJAX.pptx
JSON & AJAX.pptxJSON & AJAX.pptx
JSON & AJAX.pptx
 
Java-JSON-Jackson
Java-JSON-JacksonJava-JSON-Jackson
Java-JSON-Jackson
 

More from Yoga Raja

Php
PhpPhp
Xml
XmlXml
Database connect
Database connectDatabase connect
Database connect
Yoga Raja
 
Java Servlet
Java ServletJava Servlet
Java Servlet
Yoga Raja
 
JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGES
Yoga Raja
 
Think-Pair-Share
Think-Pair-ShareThink-Pair-Share
Think-Pair-Share
Yoga Raja
 
Minute paper
Minute paperMinute paper
Minute paper
Yoga Raja
 
Decision support system-MIS
Decision support system-MISDecision support system-MIS
Decision support system-MIS
Yoga Raja
 

More from Yoga Raja (8)

Php
PhpPhp
Php
 
Xml
XmlXml
Xml
 
Database connect
Database connectDatabase connect
Database connect
 
Java Servlet
Java ServletJava Servlet
Java Servlet
 
JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGES
 
Think-Pair-Share
Think-Pair-ShareThink-Pair-Share
Think-Pair-Share
 
Minute paper
Minute paperMinute paper
Minute paper
 
Decision support system-MIS
Decision support system-MISDecision support system-MIS
Decision support system-MIS
 

Recently uploaded

Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
Wasim Ak
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
chanes7
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Assignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docxAssignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docx
ArianaBusciglio
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
IreneSebastianRueco1
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
Delivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and TrainingDelivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and Training
AG2 Design
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 

Recently uploaded (20)

Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Assignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docxAssignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docx
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
Delivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and TrainingDelivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and Training
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 

JSON

  • 1. JSON C.A.Yogaraja Department of Computer Science and Engineering Ramco Institute of Technonlogy
  • 2. Introduction • JSON: JavaScript Object Notation. • JSON is a syntax for storing and exchanging data. • JSON is text, written with JavaScript object notation. • JSON is a lightweight data-interchange format • JSON is "self-describing" and easy to understand • JSON is language independent • JSON uses JavaScript syntax, but the JSON format is text only
  • 3. 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 • Eg: { “firstname":"John“, “age”:”20”, “skill”:[“C”,”C++”], "sale":true, "middlename":null }
  • 4. JSON Values • In JSON, values must be one of the following data types: – a string – a number – an object (JSON object) – an array – a boolean – null
  • 5. JSON Objects • Looping an Object – for-in loop • myObj = { "name":"John", "age":30, "car":null }; for (x in myObj) { document.getElementById("demo").innerHTML += x; } – name age car
  • 6. JSON Objects • Nested JSON Objects – myObj = {"name":"John", "age":30, "cars": { "car1":"Ford", "car2":"BMW", "car3":"Fiat" } } Accessing Values: x = myObj.cars.car2; Modify Values: myObj.cars.car2 = "Mercedes"; Deleting: delete myObj.cars.car2;
  • 7. JSON Arrays • myObj={"name":"John","age":30, "cars":[ "Ford", "BMW", "Fiat" ] } • Accessing: – x = myObj.cars[0]; • Accessing Via Loop: – for (i in myObj.cars) { x += myObj.cars[i]; }
  • 8. Exchanging Data • When exchanging data between a browser and a server, the data can only be text. • JSON is text, and we can convert any JavaScript object into JSON, and send JSON to the server. • We can also convert any JSON received from the server into JavaScript objects. • This way we can work with the data as JavaScript objects, with no complicated parsing and translations.
  • 9. Exchanging Data-Sending Data • A common use of JSON is to exchange data to/from a web server. • When sending data to a web server, the data has to be a string. • Convert a JavaScript object into a string with JSON.stringify(). var myObj = {name: "John", age: 31, city: "New York"}; var myJSON = JSON.stringify(myObj); document.getElementById("demo").innerHTML = myJSON;
  • 10. Exchanging Data-Sending Data Exceptions • Stringify Dates – In JSON, date objects are not allowed. The JSON.stringify() function will convert any dates into strings. – var obj = { name: "John", today: new Date()}; – var myJSON = JSON.stringify(obj); – document.getElementById("demo").innerHTML = myJSON; {"name":"John","today":"2020-01-23T04:46:38.759Z"}
  • 11. Exchanging Data-Sending Data Exceptions • Stringify Functions – In JSON, functions are not allowed as object values. – The JSON.stringify() function will remove any functions from a JavaScript object, both the key and the value: – var obj = { name: "John", age: function () {return 30;}}; – var myJSON = JSON.stringify(obj); – document.getElementById("demo").innerHTML = myJSON; {"name":"John"}
  • 12. Exchanging Data-Receiving Data • 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. var myJSON = '{"name":"John", "age":31, "city":"New York"}'; var myObj = JSON.parse(myJSON); document.getElementById("demo").innerHTML = myObj.name;
  • 13. Storing Data • When storing data, the data has to be a certain format, and regardless of where you choose to store it, text is always one of the legal formats.
  • 14. Storing Data // Storing data: myObj = {name: "John", age: 31, city: "New York"}; myJSON = JSON.stringify(myObj); localStorage.setItem("testJSON", myJSON); // Retrieving data: text = localStorage.getItem("testJSON"); obj = JSON.parse(text); document.getElementById("demo").innerHTML = obj.name;
  • 15. Function Files • A common use of JSON is to read data from a web server, and display the data in a web page. – 1: Create an array of objects. – 2: Create a JavaScript function to display the array. – 3: Use an array literal as the argument (instead of the array variable): – 4: Put the function in an external js file
  • 16. 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": "https://www.w3schools.com/js/default.asp" }, { "display": "HTML Tutorial", "url": "https://www.w3schools.com/html/default.asp" } ]
  • 17. 2: Create a JavaScript function to display the array • 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; }
  • 18. 3: Use an array literal as the argument (instead of the array variable) • myFunction([ { "display": "JavaScript Tutorial", "url": "https://www.w3schools.com/js/default.asp" }, { "display": "HTML Tutorial", "url": "https://www.w3schools.com/html/default.asp" } ]);
  • 19. 4: Put the function in an external js file • Put the function in a file named Tutorials.js: – Add the external script to your page – <script src="Tutorials.js"></script>
  • 20. JSON HTTP Request-XMLHttpRequest() • A common use of JSON is to read data from a web server, and display the data in a web page. • JSON is most commonly used in asynchronous HTTP requests. This is where an application pulls data from another application via an HTTP request on the web
  • 21. Steps for performing HttpRequest • 1: Create an array of objects. • 2: Create a JavaScript function to display the array. • 3: Create a text file • 4: Read the text file with an XMLHttpRequest
  • 22. 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": "https://www.w3schools.com/js/default.asp" }, { "display": "HTML Tutorial", "url": "https://www.w3schools.com/html/default.asp" } ]
  • 23. 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; } • Call myFunction() with myArray as argument: • myFunction(myArray);
  • 24. 3: Create a text file • Put the array literal in a file named myTutorials.txt: [ { "display": "JavaScript Tutorial", "url": "https://www.w3schools.com/js/default.asp" }, { "display": "HTML Tutorial", "url": "https://www.w3schools.com/html/default.asp" } ]
  • 25. 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.open("GET", url, true); xmlhttp.send(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var myArr = JSON.parse(this.responseText); myFunction(myArr); } };
  • 26. XMLHttpRequest object • Update a web page without reloading the page • Request data from a server - after the page has loaded • Receive data from a server - after the page has loaded • Send data to a server - in the background
  • 27. Creating an XMLHttpRequest Object • var xhttp = new XMLHttpRequest();
  • 28. onreadystatechange Event • The readyState property holds the status of the XMLHttpRequest. • The onreadystatechange event is triggered every time the readyState changes. • During a server request, the readyState changes from 0 to 4: • 0: request not initialized 1: server connection established 2: request received 3: processing request 4: request finished and response is ready
  • 29. onreadystatechange Event • In the onreadystatechange property, specify a function to be executed when the readyState changes: – xhttp.onreadystatechange = function() • When readyState is 4 and status is 200, the response is ready: – if (this.readyState == 4 && this.status == 200)
  • 30. XMLHttpRequest Properties and Methods Method Description new XMLHttpRequest() Creates a new XMLHttpRequest object open(method, url, async) Specifies the type of request method: the type of request: GET or POST url: the file location async: true (asynchronous) or false (synchronous) send() Sends a request to the server (used for GET) send(string) Sends a request string to the server (used for POST)
  • 31. XMLHttpRequest Properties and Methods Method Description onreadystatechange A function to be called when the readyState property changes readyState 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 status 200: OK 404: Page not found responseText The response data as a string responseXML The response data as XML data