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

Más contenido relacionado

La actualidad más candente (20)

Introduction to JSON & AJAX
Introduction to JSON & AJAXIntroduction to JSON & AJAX
Introduction to JSON & AJAX
 
Json
JsonJson
Json
 
Json
JsonJson
Json
 
J s-o-n-120219575328402-3
J s-o-n-120219575328402-3J s-o-n-120219575328402-3
J s-o-n-120219575328402-3
 
Intro to JSON
Intro to JSONIntro to JSON
Intro to JSON
 
Json tutorial, a beguiner guide
Json tutorial, a beguiner guideJson tutorial, a beguiner guide
Json tutorial, a beguiner guide
 
JSON
JSONJSON
JSON
 
Java script
Java scriptJava script
Java script
 
Javascript2839
Javascript2839Javascript2839
Javascript2839
 
java script json
java script jsonjava script json
java script json
 
Json the-x-in-ajax1588
Json the-x-in-ajax1588Json the-x-in-ajax1588
Json the-x-in-ajax1588
 
Ajax
AjaxAjax
Ajax
 
Jsonsaga 100605143125-phpapp02
Jsonsaga 100605143125-phpapp02Jsonsaga 100605143125-phpapp02
Jsonsaga 100605143125-phpapp02
 
Json
JsonJson
Json
 
Json
JsonJson
Json
 
Json
JsonJson
Json
 
JSON Processing in the Database using PostgreSQL 9.4 :: Data Wranglers DC :: ...
JSON Processing in the Database using PostgreSQL 9.4 :: Data Wranglers DC :: ...JSON Processing in the Database using PostgreSQL 9.4 :: Data Wranglers DC :: ...
JSON Processing in the Database using PostgreSQL 9.4 :: Data Wranglers DC :: ...
 
Json
JsonJson
Json
 
JSON Injection
JSON InjectionJSON Injection
JSON Injection
 
ActiveRecord vs Mongoid
ActiveRecord vs MongoidActiveRecord vs Mongoid
ActiveRecord vs Mongoid
 

Destacado

Ajax Tutorial
Ajax TutorialAjax Tutorial
Ajax Tutorialoscon2007
 
Open Ldap Integration and Configuration with Lifray 6.2
Open Ldap Integration and Configuration with Lifray 6.2Open Ldap Integration and Configuration with Lifray 6.2
Open Ldap Integration and Configuration with Lifray 6.2Vinaykumar Hebballi
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajaxNir Elbaz
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slidesSmithss25
 

Destacado (6)

Ajax Tutorial
Ajax TutorialAjax Tutorial
Ajax Tutorial
 
Open Ldap Integration and Configuration with Lifray 6.2
Open Ldap Integration and Configuration with Lifray 6.2Open Ldap Integration and Configuration with Lifray 6.2
Open Ldap Integration and Configuration with Lifray 6.2
 
Json vs Gson vs Jackson
Json vs Gson vs JacksonJson vs Gson vs Jackson
Json vs Gson vs Jackson
 
Ajax Ppt 1
Ajax Ppt 1Ajax Ppt 1
Ajax Ppt 1
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajax
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slides
 

Similar a JSON(JavaScript Object Notation)

JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)Skillwise Group
 
JSON & AJAX.pptx
JSON & AJAX.pptxJSON & AJAX.pptx
JSON & AJAX.pptxdyumna2
 
Internet and Web Technology (CLASS-8) [jQuery and JSON] | NIC/NIELIT Web Tech...
Internet and Web Technology (CLASS-8) [jQuery and JSON] | NIC/NIELIT Web Tech...Internet and Web Technology (CLASS-8) [jQuery and JSON] | NIC/NIELIT Web Tech...
Internet and Web Technology (CLASS-8) [jQuery and JSON] | NIC/NIELIT Web Tech...Ayes Chinmay
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on AndroidSven Haiges
 
Web Development Course - AJAX & JSON by RSOLUTIONS
Web Development Course - AJAX & JSON by RSOLUTIONSWeb Development Course - AJAX & JSON by RSOLUTIONS
Web Development Course - AJAX & JSON by RSOLUTIONSRSolutions
 
PostgreSQL's Secret NoSQL Superpowers
PostgreSQL's Secret NoSQL SuperpowersPostgreSQL's Secret NoSQL Superpowers
PostgreSQL's Secret NoSQL SuperpowersAmanda Gilmore
 
jQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyjQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyHuiyi Yan
 
JQuery Presentation
JQuery PresentationJQuery Presentation
JQuery PresentationSony Jain
 
Introduction to Prototype JS Framework
Introduction to Prototype JS FrameworkIntroduction to Prototype JS Framework
Introduction to Prototype JS FrameworkMohd Imran
 
Ajax for dummies, and not only.
Ajax for dummies, and not only.Ajax for dummies, and not only.
Ajax for dummies, and not only.Nerd Tzanetopoulos
 
JSON Schema: Your API's Secret Weapon
JSON Schema: Your API's Secret WeaponJSON Schema: Your API's Secret Weapon
JSON Schema: Your API's Secret WeaponPete Gamache
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairMark
 
Tips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET ApplicationTips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET ApplicationJoni
 
Contacto server API in PHP
Contacto server API in PHPContacto server API in PHP
Contacto server API in PHPHem Shrestha
 

Similar a JSON(JavaScript Object Notation) (20)

JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)
 
Json
JsonJson
Json
 
JSON & AJAX.pptx
JSON & AJAX.pptxJSON & AJAX.pptx
JSON & AJAX.pptx
 
Ajax - a quick introduction
Ajax - a quick introductionAjax - a quick introduction
Ajax - a quick introduction
 
Internet and Web Technology (CLASS-8) [jQuery and JSON] | NIC/NIELIT Web Tech...
Internet and Web Technology (CLASS-8) [jQuery and JSON] | NIC/NIELIT Web Tech...Internet and Web Technology (CLASS-8) [jQuery and JSON] | NIC/NIELIT Web Tech...
Internet and Web Technology (CLASS-8) [jQuery and JSON] | NIC/NIELIT Web Tech...
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
Web Development Course - AJAX & JSON by RSOLUTIONS
Web Development Course - AJAX & JSON by RSOLUTIONSWeb Development Course - AJAX & JSON by RSOLUTIONS
Web Development Course - AJAX & JSON by RSOLUTIONS
 
PostgreSQL's Secret NoSQL Superpowers
PostgreSQL's Secret NoSQL SuperpowersPostgreSQL's Secret NoSQL Superpowers
PostgreSQL's Secret NoSQL Superpowers
 
jQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyjQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journey
 
JQuery Presentation
JQuery PresentationJQuery Presentation
JQuery Presentation
 
Introduction to Prototype JS Framework
Introduction to Prototype JS FrameworkIntroduction to Prototype JS Framework
Introduction to Prototype JS Framework
 
Ajax for dummies, and not only.
Ajax for dummies, and not only.Ajax for dummies, and not only.
Ajax for dummies, and not only.
 
JSON Schema: Your API's Secret Weapon
JSON Schema: Your API's Secret WeaponJSON Schema: Your API's Secret Weapon
JSON Schema: Your API's Secret Weapon
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love Affair
 
Os Pruett
Os PruettOs Pruett
Os Pruett
 
AJAX
AJAXAJAX
AJAX
 
Tips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET ApplicationTips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET Application
 
Contacto server API in PHP
Contacto server API in PHPContacto server API in PHP
Contacto server API in PHP
 
Php sql-android
Php sql-androidPhp sql-android
Php sql-android
 
JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2
 

Más de Raghu nath

Ftp (file transfer protocol)
Ftp (file transfer protocol)Ftp (file transfer protocol)
Ftp (file transfer protocol)Raghu nath
 
Javascript part1
Javascript part1Javascript part1
Javascript part1Raghu nath
 
Regular expressions
Regular expressionsRegular expressions
Regular expressionsRaghu nath
 
Selection sort
Selection sortSelection sort
Selection sortRaghu nath
 
Binary search
Binary search Binary search
Binary search Raghu nath
 
Stemming algorithms
Stemming algorithmsStemming algorithms
Stemming algorithmsRaghu nath
 
Step by step guide to install dhcp role
Step by step guide to install dhcp roleStep by step guide to install dhcp role
Step by step guide to install dhcp roleRaghu nath
 
Network essentials chapter 4
Network essentials  chapter 4Network essentials  chapter 4
Network essentials chapter 4Raghu nath
 
Network essentials chapter 3
Network essentials  chapter 3Network essentials  chapter 3
Network essentials chapter 3Raghu nath
 
Network essentials chapter 2
Network essentials  chapter 2Network essentials  chapter 2
Network essentials chapter 2Raghu nath
 
Network essentials - chapter 1
Network essentials - chapter 1Network essentials - chapter 1
Network essentials - chapter 1Raghu nath
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2Raghu nath
 
python chapter 1
python chapter 1python chapter 1
python chapter 1Raghu nath
 
Linux Shell Scripting
Linux Shell ScriptingLinux Shell Scripting
Linux Shell ScriptingRaghu nath
 
Adv excel® 2013
Adv excel® 2013Adv excel® 2013
Adv excel® 2013Raghu nath
 

Más de Raghu nath (20)

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

Último

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterMateoGardella
 

Último (20)

Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 

JSON(JavaScript Object Notation)

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