JSON

JavaScript Object Notation (JSON) is a lightweight standard for data interchange. It offers several advantages over XML for data interchange such as it can be used for serializing and transmitting structured data over a network. JSON is used with JavaScript based applications and is primarily used to transmit data between client and server. It is easier to use than XML.

JSON Example

{
 "car": [
 {
   "make":"Toyota",
   "model":"Corolla:
 },
 {
   "make":"Honda",
   "model":"Civic:
 }]
}

XML Example

<cars>
 <car>
   <make>Toyota</make>
   <model>Corolla</model>
 </car>
 <car>
   <make>Honda</make>
   <model>Civic</model>
 </car>
</car>  

JSON Example

In XML, you need to use a parser to access data. JSON data can be converted to JavaScript objects for easy access by standard JavaScript functions.

<html>
<body>
<h2>Using JavaScript to create JSON object</h2>
<p id="jsontest"></p>
<script>
// JSON data
var text = '{"make":"Toyota","model":"Corolla","price":"$17,000"}'
// create JSON object
var obj = JSON.parse(text);
// access data
document.getElementById("jsontest").innerHTML =
"Jim bought a " + obj.make + " " + obj.model + " for " + obj.price;
</script>
</body>
</html>

Output:

Using JavaScript to create JSON object

Jim bought a Toyota Corolla for $17,000

JSON.parse() function converts JSON to an object. document.getElementById() is used to access JavaScript objects.

Working with JSON arrays

JSON syntax also supports arrays. Following is an example of working with JSON arrays using JavaScript.

<html>
<body>
<p id="jsontest"></p>
<script>
var cars = [
 { "make":"Toyota","model":"Corolla" }, 
 { "make":"Honda","model":"Civic" },
 { "make":"Nissan","model":"Altima" },
];
document.getElementById("jsontest").innerHTML =
"List of Makes: <br/>- " + cars[0].make + "<br/>- " + cars[1].make + "<br/>- " + cars[2].make;
</script>
</body>
</html>

Output:

List of Makes:
- Toyota
- Honda
- Nissan

Using a JSON file

JSON code can be stored in a JSON file. This is a more practical way of working with JSON. First create a JSON file and save it. The create an HTML file and access the JSON file from it and access its data.

This following example will only work in a client-server environment

cars.json

[
{
"make": "Toyota",
"model": "Corolla",
"url": "http://en.wikipedia.org/wiki/Toyota_Corolla"
},
{
"make": "Honda",
"model": "Civic",
"url": "http://en.wikipedia.org/wiki/Honda_Civic"
},
{
"make": "Nissan",
"model": "Altima",
"url": "http://en.wikipedia.org/wiki/Nissan_Altima"
}
]

jsontest.html

<html>
<body>

<div id="jsontest"></div>

<script>
var xmlhttp = new XMLHttpRequest();
var url = "cars.json";

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].make + '</a><br>';
   }
   document.getElementById("jsontest").innerHTML = out;
}
</script>

</body>
</html>

output

Toyota
Honda
Nissan

JSON with PHP and MySQL

JSON works beautifully with PHP and MySQL. Let's assume that you have a database table with a list of vehicle makes and models. The following example shows how to extract this information and display it using JSON. Note that this example will only work in a client-server environment.

json.php

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

// database connection
$host = 'aaaa';
$db = 'bbbb';
$user = 'cccc';
$pass = 'dddd';

$conn = new mysqli($host, $user, $pass, $db);
$result = $conn->query("SELECT make, model from cars limit 10");

$out = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
   if ($out != "[") {$outp .= ",";}
   $out .= '{"make":"'  . $rs["make"] . '",';
   $out .= '"model":"'. $rs["model"]     . '"}'; 
}
$out .="]";
$conn->close();
echo($outp);

jsontest.html

<html>
<body>

<h1>Cars</h1>
<div id="jsontest"></div>

<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://www.mysite.com/json.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].de +
       "</td><td>" +
       arr[i].metaphone +
       "</td></tr>";
   }
   out += "</table>"
   document.getElementById("jsontest").innerHTML = out;
}
</script>

</body>
</html>

output

Cars

ToyotaCorolla
HondaCivic
NissanAltima
Technologies: