JSON
JSON
By:-
Vilas Machhi
Introduction
• JSON: JavaScript Object Notation.
• JSON is a syntax for storing and exchanging data.
• JSON is text, written with JavaScript object notation.
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.
Why use JSON?
• Since the JSON format is text only, it can easily be sent to and from a server, and used as a
data format by any programming language.
• JavaScript has a built in function to convert a string, written in JSON format, into native
JavaScript objects:
JSON.parse()
• So, if you receive data from a server, in JSON format, you can use it like any other JavaScript
object.
JSON Syntax
Syntax Rules
• 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
"name":"John"
Note: JSON names require double quotes. JavaScript names don't.
JSON Syntax
JSON - Evaluates to JavaScript Objects
• The JSON format is almost identical to JavaScript objects.
• In JSON, keys must be strings, written with double quotes:
JSON
{ "name":"John" }
• In JavaScript, keys can be strings, numbers, or identifier names:
JavaScript
{ name:"John" }
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 Syntax
• In JavaScript values can be all of the above, plus any other valid JavaScript
expression, including:
• a function
• a date
• undefined
• In JSON, string values must be written with double quotes:
JSON
{ "name":"John" }
• In JavaScript, you can write string values with double or single quotes:
JavaScript
{ name:'John' }
JSON Files
• The file type for JSON files is ".json"
• The MIME type for JSON text is "application/json"
JSON Data Types
Valid Data Types
• 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 values cannot be one of the following data types:
• a function
• a date
• undefined
JSON Strings
• Strings in JSON must be written in double quotes.
Example
{ "name":"John" }
JSON Data Types
JSON Numbers JSON Arrays
• Numbers in JSON must be an integer or a • Values in JSON can be arrays.
floating point. Example
Example {
{ "age":30 } "employees":[ "John", "Anna", "Peter" ]
}
JSON Objects
JSON Booleans
• Values in JSON can be objects.
• Values in JSON can be true/false.
Example Example
{
{ "sale":true }
"employee":{ "name":"John", "age":30,
"city":"New York" } JSON null
} • Values in JSON can be null.
• Objects as values in JSON must follow the Example
same rules as JSON objects. { "middlename":null }
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 object and assign data to it, like this:
Example
var person = { name: "John", age: 31, city: "New York" };
• You can access a JavaScript object like this:
Example
// returns John
person.name;
• It can also be accessed like this:
Example
// returns John
person["name"];
• Data can be modified like this:
Example
person.name = "Gilbert";
• It can also be modified like this:
Example
person["name"] = "Gilbert";
JSON Objects
Object Syntax
Example
{ "name":"John", "age":30, "car":null }
• JSON objects are surrounded by curly braces {}.
• JSON objects are written in key/value pairs.
• Keys must be strings, and values must be a valid JSON data type (string, number, object, array,
boolean or null).
• Keys and values are separated by a colon.
• Each key/value pair is separated by a comma.
Accessing Object Values
• You can access the object values by using dot (.) notation:
Example
myObj = { "name":"John", "age":30, "car":null };
x = myObj.name;
• You can also access the object values by using bracket ([]) notation:
Example
myObj = { "name":"John", "age":30, "car":null };
x = myObj["name"];
Looping an Object
• You can loop through object properties by using the for-in loop:
Example
myObj = { "name":"John", "age":30, "car":null };
for (x in myObj) {
document.getElementById("demo").innerHTML += x;
}
• In a for-in loop, use the bracket notation to access the property values:
Example
myObj = { "name":"John", "age":30, "car":null };
for (x in myObj) {
document.getElementById("demo").innerHTML += myObj[x];
Nested JSON Objects
• Values in a JSON object can be another JSON object.
Example
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:
• You can also use the bracket notation to modify a value in a JSON object:
Example
myObj.cars.car2 = "Mercedes";
Example
myObj.cars["car2"] = "Mercedes";
Delete Object Properties
• Use the delete keyword to delete properties from a JSON object:
Example
delete myObj.cars.car2;
JSON vs XML
• Both JSON and XML can be used to XML Example
receive data from a web server. <employees>
Note:-You should avoid using functions in JSON, the functions will lose their
scope, and you would have to use eval() to convert them back into functions.
JSON.stringify()
• When sending data to a web server, the data has to be a string.
• Convert a JavaScript object into a string with JSON.stringify().
Stringify a JavaScript Object
• Imagine we have this object in JavaScript:
var obj = { name: "John", age: 30, city: "New York" };
• Use the JavaScript function JSON.stringify() to convert it into a string.
var myJSON = JSON.stringify(obj);
• The result will be a string following the JSON notation.
• myJSON is now a string, and ready to be sent to a server:
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:
• Imagine we have this array in JavaScript:
var arr = [ "John", "Peter", "Sally", "Jane" ];
• Use the JavaScript function JSON.stringify() to convert it into a string.
• var myJSON = JSON.stringify(arr);
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 PHP
• 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 = array("name"=>'john', "age"=>37, "city"=>'New York');
echo json_encode($myObj);
?>
The Client JavaScript
• Here is a JavaScript on the client, using an AJAX call to request the PHP file from the example
above:
Example
• Use JSON.parse() to convert the result into a JavaScript object:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
};