1.3 Study Material For Section-I-Part-I - JSON
1.3 Study Material For Section-I-Part-I - JSON
(Resource: www.w3schools.com)
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.
JSON uses JavaScript syntax, but the JSON format is text only.
Text can be read and used as a data format by any programming language.
Sending Data
If you have data stored in a JavaScript object, you can convert the object into JSON, and
send it to a server:
<script>
var myObj = {name: "John", age: 31, city: "New York"};
var myJSON = JSON.stringify(myObj);
window.location = "demo_json.php?x=" + myJSON;
</script>
Receiving Data
If you receive data in JSON format, you can convert it into a JavaScript object:
<script>
var myJSON = '{"name":"John", "age":31, "city":"New York"}';
var myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj.name;
</script>
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. JSON makes it possible to
store JavaScript objects as text.
// 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;
A name/value pair consists of a field name (in double quotes), followed by a colon,
followed by a value:
"name":"Narendra"
{"name":"Narendra"}
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 JavaScript
{"name":"Narendra"}
{name:'Narendra'}
With JavaScript you can create an object and assign data to it, like this:
JSON Files
The file type for JSON files is ".json"
The MIME type for JSON text is "application/json"
JSON vs XML
<employees> {"employees":[
<employee> { "firstName":"John", "lastName"
<firstName>John</firstName> <lastName>Doe :"Doe" },
</lastName> { "firstName":"Anna", "lastName"
</employee> :"Smith" },
<employee> { "firstName":"Peter", "lastName
<firstName>Anna</firstName> <lastName>Smi ":"Jones" }
th</lastName> ]}
</employee>
<employee>
<firstName>Peter</firstName> <lastName>Jo
nes</lastName>
</employee>
</employees>
The biggest difference is: XML has to be parsed with an XML parser. JSON can be parsed by a
standard JavaScript function.
Using XML
Using JSON
a string
a number
an object (JSON object)
an array
a boolean
null
a function
a date
undefined
JSON Strings
Strings in JSON must be written in double quotes. : { "name":"John" }
JSON Numbers
Numbers in JSON must be an integer or a floating point. : { "age":30 }
JSON Objects
Values in JSON can be objects:
{
"employee":{ "name":"John", "age":30, "city":"New York" }
}
Objects as values in JSON must follow the same rules as JSON objects.
JSON Arrays
Values in JSON can be arrays.
Example
{
"employees":[ "John", "Anna", "Peter" ]
}
JSON Booleans
Values in JSON can be true/false : { "sale":true }
JSON null
Values in JSON can be null : { "middlename":null }
JSON.parse()
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.
Use the JavaScript function JSON.parse() to convert text into a JavaScript object:
<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p id="demo"></p>
<script>
var txt = '{"name":"John", "age":30, "city":"New York"}'
var obj = JSON.parse(txt);
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;
</script>
</body>
</html>
As long as the response from the server is written in JSON format, you can parse the string into a
JavaScript object.
Array as JSON
When using the JSON.parse() on a JSON derived from an array, the method will return a
JavaScript array, instead of a JavaScript object.
Parsing Dates
Parsing Functions
JSON.stringify()
When sending data to a web server, the data has to be a string.
Example
var obj = { name: "John", age: 30, city: "New York" };
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
Stringify a JavaScript Array
It is also possible to stringify JavaScript arrays:
Example
var arr = [ "John", "Peter", "Sally", "Jane" ];
var myJSON = JSON.stringify(arr);
document.getElementById("demo").innerHTML = myJSON;
Exceptions
Stringify Dates
In JSON, date objects are not allowed. The JSON.stringify() function will convert any dates into
strings.
Example
var obj = { name: "John", today: new Date(), city : "New York" };
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
Stringify Functions
The JSON.stringify() function will remove any functions from a JavaScript object, both the key
and the value:
Example
var obj = { name: "John", age: function () {return 30;}, city: "New York"};
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
This can be omitted if you convert your functions into strings before running
the JSON.stringify() function.
Example
var obj = { name: "John", age: function () {return 30;}, city: "New York" };
obj.age = obj.age.toString();
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
JSON Objects
Object Syntax : { "name":"John", "age":30, "car":null }
Keys must be strings, and values must be a valid JSON data type (string, number,
object, array, boolean or null).
You can also access the object values by using bracket ([]) notation:
Looping an Object
You can loop through object properties by using the for-in loop:
In a for-in loop, use the bracket notation to access the property values:
myObj = {
"name":"John",
"age":30,
"cars": {
"car1":"Ford",
"car2":"BMW",
"car3":"Fiat"
}
}
You can access nested JSON objects by using the dot notation or bracket notation:
x = myObj.cars.car2;
// or:
x = myObj.cars["car2"];
Modify Values
You can use the dot notation to modify any value in a JSON object:
myObj.cars.car2 = "Mercedes";
You can also use the bracket notation to modify a value in a JSON object:
myObj.cars["car2"] = "Mercedes";
delete myObj.cars.car2;
JSON Arrays
Arrays as JSON Objects
[ "Ford", "BMW", "Fiat" ]
In JSON, array values must be of type string, number, object, array, boolean or null.
In JavaScript, array values can be all of the above, plus any other valid JavaScript expression,
including functions, dates, and undefined.
{
"name":"John",
"age":30,
"cars":[ "Ford", "BMW", "Fiat" ]
}
Example
x = myObj.cars[0];
for (i in myObj.cars) {
x += myObj.cars[i];
}
myObj = {
"name":"John",
"age":30,
"cars": [
{ "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
{ "name":"BMW", "models":[ "320", "X3", "X5" ] },
{ "name":"Fiat", "models":[ "500", "Panda" ] }
]
}
To access arrays inside arrays, use a for-in loop for each array:
for (i in myObj.cars) {
x += "<h1>" + myObj.cars[i].name + "</h1>";
for (j in myObj.cars[i].models) {
x += myObj.cars[i].models[j];
}
}
myObj.cars[1] = "Mercedes";
delete myObj.cars[1];
JSON PHP
A common use of JSON is to read data from a web server, and display the data in a web
page.
The PHP File
PHP has some built-in functions to handle JSON.
Objects in PHP can be converted into JSON by using the PHP function json_encode():
PHP file
<?php
$myObj->name = "John";
$myObj->age = 30;
$myObj->city = "New York";
$myJSON = json_encode($myObj);
echo $myJSON;
?>
Example
Use JSON.parse() to convert the result into a JavaScript object:
PHP Database
PHP is a server side programming language, and can be used to access a database.
Imagine you have a database on your server, and you want to send a request to it from the client
where you ask for the 10 first rows in a table called "customers".
On the client, make a JSON object that describes the numbers of rows you want to return.
Before you send the request to the server, convert the JSON object into a string and send it as a
parameter to the url of the PHP page
obj = { "limit":10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "json_demo_db.php?x=" + dbParam, true);
xmlhttp.send();