0% found this document useful (0 votes)
24 views23 pages

JSON

Uploaded by

Dewang Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views23 pages

JSON

Uploaded by

Dewang Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 23

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>

• The following JSON and XML examples <employee>

both define an employees object, with an <firstName>John</firstName>


<lastName>Doe</lastName>
array of 3 employees:
</employee>
JSON Example <employee>
{"employees":[ <firstName>Anna</firstName>
<lastName>Smith</lastName>
{ "firstName":"John", "lastName":"Doe" },
</employee>
{ "firstName":"Anna", <employee>
"lastName":"Smith" },
<firstName>Peter</firstName>
{ "firstName":"Peter", "lastName":"Jones" } <lastName>Jones</lastName>
</employee>
]}
</employees>
JSON vs XML
• JSON is Like XML Because
• Both JSON and XML are "self describing" (human readable)
• Both JSON and XML are 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
• JSON is Unlike XML Because
• JSON doesn't use end tag
• JSON is shorter
• JSON is quicker to read and write
• JSON can use arrays
• The biggest difference is:
• XML has to be parsed with an XML parser. JSON can be parsed by a
standard JavaScript function.
JSON vs XML
Why JSON is Better Than XML
• XML is much more difficult to parse than JSON.
• JSON is parsed into a ready-to-use JavaScript object.

• 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
• Using JSON
• Fetch a JSON string
• JSON.Parse the JSON string
JSON.parse()
• A common use of JSON is to exchange data to/from a web server.
• 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.
• Imagine we received this text from a web server:
'{ "name":"John", "age":30, "city":"New York"}'
• Use the JavaScript function JSON.parse() to convert text into a
JavaScript object:
var obj = JSON.parse('{ "name":"John", "age":30, "city":"New
York"}');
• Make sure the text is written in JSON format, or else you will get a
syntax error.
JSON From the Server
• You can request JSON from the server by using an AJAX request
• As long as the response from the server is written in JSON format, you
can parse the string 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;
}
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();
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.
• The JSON returned from the server is an array:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myArr[0];
}
};
xmlhttp.open("GET", "json_demo_array.txt", true);
xmlhttp.send();
Exception
Parsing Dates
• Date objects are not allowed in JSON.
• If you need to include a date, write it as a string.
• You can convert it back into a date object later:
• you can use the second parameter of the JSON.parse() function, called reviver
• The reviver parameter is a function that checks each property, before returning the value.
Example
Convert a string into a date:
var text = '{ "name":"John", "birth":"1986-12-14", "city":"New York"}';
var obj = JSON.parse(text);
obj.birth = new Date(obj.birth);
document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth;
Example
Convert a string into a date, using the reviver function:
var text = '{ "name":"John", "birth":"1986-12-14", "city":"New York"}';
var obj = JSON.parse(text, function (key, value) {
if (key == "birth") {
return new Date(value);
} else {
return value;
}
});
Parsing Functions
• Functions are not allowed in JSON.
• If you need to include a function, write it as a string.
• You can convert it back into a function later:
Example
• Convert a string into a function:
var text = '{ "name":"John", "age":"function () {return 30;}", "city":"New York"}';
var obj = JSON.parse(text);
obj.age = eval("(" + obj.age + ")");

document.getElementById("demo").innerHTML = obj.name + ", " + obj.age();

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;
}
};

You might also like