JSON
JSON: JavaScript Object Notation.
JSON is a syntax for storing and exchanging data.
JSON is an easier-to-use alternative to XML.
The following JSON example defines an employees object, with an array of 3 employee records:
JSON Example
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}
XML Example
<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>
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 - Introduction
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.
Try it Yourself
With our editor, you can edit JavaScript code online and click on a button to view the result: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>
Much Like XML Because
- Both JSON and XML is "self describing" (human readable)
- Both JSON and XML is hierarchical (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
XML has to be parsed with an XML parser, JSON can be parsed by a standard JavaScript function.
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
- Fetch a JSON string
- JSON.Parse the JSON string
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
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:
Example
"firstName":"John"
JSON names require double quotes. JavaScript names don't. |
JSON Values
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
JSON Objects
JSON objects are written inside curly braces.Just like JavaScript, JSON objects can contain multiple name/values pairs:
Example
{"firstName":"John", "lastName":"Doe"}
JSON Arrays
JSON arrays are written inside square brackets.Just like JavaScript, a JSON array can contain multiple objects:
Example
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter","lastName":"Jones"}
]
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:
Example
var employees =
[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter","lastName": "Jones"}
];
Example
// returns John Doeemployees[0].firstName + " " + employees[0].lastName;
Example
// returns John Doeemployees[0]["firstName"] +
" " + employees[0]["lastName"];
Example
employees[0].firstName = "Gilbert";
Example
employees[0]["firstName"] = "Gilbert";
JSON Files
- The file type for JSON files is ".json"
- The MIME type for JSON text is "application/json"
JSON How To
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" } ]}';
The JavaScript function JSON.parse(text) can be used to convert a JSON text into a JavaScript object:
var obj = JSON.parse(text);
Example
<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:Example
var obj = eval ("(" + text + ")");
The eval() function can compile and execute any JavaScript. This represents a potential security problem. Try to avoid it. |
A JSON parser will recognize only JSON text and will not compile scripts.
In browsers that provide native JSON support, JSON parsers are also faster.
Native JSON support is included in all major browsers and in the latest ECMAScript (JavaScript) standard:
Web Browsers Support |
---|
|
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.
JSON Example
This example reads a menu from myTutorials.txt, and displays the menu in a web page:JSON Example
<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:
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"
}
]
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;
}
Example
myFunction(myArray);
Put the array literal in a file named myTutorials.txt:
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"
}
]
Write an XMLHttpRequest to read the text file, and use myFunction() to display the array:
XMLHttpRequest
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();
JSON Function Files
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 function files.
JSON Example
This example reads a menu from
myTutorials.js, and displays the menu in a web
page:
JSON Example
<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>
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": "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:
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;
}
Call myFunction() with myArray as argument:
Example
myFunction(myArray);
3: Use an array literal as the argument (instead of the array
variable):
Call myFunction() with an array literal
as argument:
Calling myFunction()
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"
}
]);
4: Put the function call in an external js file
Put the function call this in a file named myTutorials.js:
myTutorials.js
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"
}
]);
Add the external script to your page (instead of the function call):
Add External Script
<script src="myTutorials.js"></script>
JSON Example
JSON Example
This example reads JSON data from a web server running PHP and MySQL:
Customers.html
<!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>
The PHP Code on the Server
This is the PHP code running on the server:
<?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);
?>
A Styled Version
Customers.html
<!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>
No comments:
Post a Comment