Module 5
Module 5
(JavaScript Object
Notation)
Introduction to JSON
• JSON stands for JavaScript Object Notation.
• It is a format for structuring data.
• This format is used by different web applications to communicate with each other.
• JSON is the replacement of the XML data exchange format in JSON. It is easy to
struct the data compare to XML.
• It supports data structures like arrays and objects and the JSON documents that
are rapidly executed on the server.
• It is also a Language-Independent format that is derived from JavaScript.
• The official media type for the JSON is application/json and to save those
file .json extension.
Features of JSON:
• Easy to understand: JSON is easy to read and write.
• Format: It is a text-based interchange format. It can store any kind of data in an
array of video, audio, and image anything that you required.
• Support: It is light-weighted and supported by almost every language and OS. It
has a wide range of support for the browsers approx each browser supported by
JSON.
• Dependency: It is an Independent language that is text-based. It is much faster
compared to other text-based structured data.
Uses of JSON
• It is used while writing JavaScript based applications that includes browser extensions
and websites.
• JSON format is used for serializing and transmitting structured data over network
connection.
• Web services and APIs use JSON format to provide public data.
{
"id":"01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},
{
"id":"07",
"language": "C++",
"edition": "second",
"author": "E.Balagurusamy"
}
]
}
<html>
<head>
<title>JSON example</title>
<script language = "javascript" >
var object1 = { "language" : "Java", "author" : "herbert schildt" };
document.write("<h1>JSON with JavaScript example</h1>");
document.write("<br>");
document.write("<h3>Language = " + object1.language+"</h3>");
document.write("<h3>Author = " + object1.author+"</h3>");
document.write("<hr />");
document.write(object2.language + " programming language can be studied " + "from book written by " +
object2.author);
document.write("<hr />");
</script>
</head>
<body>
</body>
Advantages of JSON:
• JSON stores all the data in an array so data transfer makes easier. That’s why
JSON is the best for sharing data of any size even audio, video, etc.
• Its syntax is very easy to use. Its syntax is very small and light-weighted that’s the
reason that it executes and response in a faster way.
• JSON has a wide range for the browser support compatibility with the operating
systems, it doesn’t require much effort to make it all browser compatible.
• On the server-side parsing the most important part that developers want, if the
parsing will be fast on the server side then the user can get the fast response, so in
this case JSON server-side parsing is the strong point compare tot others.
Disadvantages of JSON:
• The main disadvantage for JSON is that there is no error handling in JSON, if
there was a slight mistake in the JSON script then you will not get the structured
data.
• JSON becomes quite dangerous when you used it with some unauthorized
browsers. Like JSON service return a JSON file wrapped in a function call that
has to be executed by the browsers if the browsers are unauthorized then your data
can be hacked.
• JSON has limited supported tools that we can use during JSON development.
Why Use JSON?
• The JSON format is syntactically similar to the code for creating JavaScript objects.
Because of this, a JavaScript program can easily convert JSON data into JavaScript
objects.
• Since the format is text only, JSON data can easily be sent between computers, and used
by any programming language.
• JavaScript has a built in function for converting JSON strings into JavaScript objects:
JSON.parse()
• JavaScript also has a built in function for converting an object into a JSON string:
JSON.stringify()
JSON - Syntax
JSON syntax is basically considered as a subset of JavaScript syntax; it includes the
following −
• Curly braces hold objects and each name is followed by ':'(colon), the name/value
pairs are separated by , (comma).
{
"id": "01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},
{
"id": "07",
"language": "C++",
"edition": "second",
"author": "E.Balagurusamy"
}
]
Data Structure supported by JSON
JSON supports the following two data structures −
Sr.
Type & Description
No.
1 Integer
Digits 1-9, 0 and positive or negative
2 Fraction
Fractions like .3, .9
3 Exponent
Exponent like e, e+, e-, E, E+, E-
Example
Syntax
var json-object-name = { string : number_value, .......}
Example:
{ "age": 20 }
{ "percentage": 82.44}
String
• It is a sequence of zero or more double quoted Unicode characters with backslash
escaping.
• Character is a single character string i.e. a string with length 1.
• JSON strings must be written in double quotes like C-language there are various
special characters(Escape Characters) in JSON that you can use in strings such
as \ (backslash), / (forward slash), b (backspace), n (new line), r (carriage return), t
(horizontal tab), etc.
Syntax
var json-object-name = { string : "string value", .......}
Example
{ "name":"Vivek" }
{ "city":"Delhi\/India" }
• These are enclosed in square brackets which means that array begins with .[. and ends
with .]..
• Arrays should be used when the key names are sequential integers.
Syntax
[ value, .......]
Example
• Example showing array containing multiple objects −
{
"books": [
{ "language":"Java" , "edition":"second" },
{ "language":"C++" , "lastName":"fifth" },
{ "language":"C" , "lastName":"third" }
]
}
Object
• It is an unordered set of name/value pairs.
• Objects are enclosed in curly braces that is, it starts with '{' and ends with '}'.
• Each name is followed by ':'(colon) and the key/value pairs are separated by ,
(comma).
• The keys must be strings and should be different from each other.
• Objects should be used when the key names are arbitrary strings.
Object: Syntax and Example
Syntax
{ string : value, .......}
Example
{
"id": "011A",
"language": "JAVA",
"price": 500,
}
Whitespace
• It can be inserted between any pair of tokens. It can be added to make a code more
readable. Example shows declaration with and without whitespace −
Syntax
{string:" ",....}
Example
var obj1 = {"name": "Sachin Tendulkar"}
var obj2 = {"name": "SauravGanguly"}
null
• It means empty type.
Syntax
null
Example
var i = null;
if(i == 1) {
document.write("<h1>value is 1</h1>");
} else {
document.write("<h1>value is null</h1>");
}
JSON Value
It includes −
• number (integer or floating point)
• string
• boolean
• array
• object
• null
JSON Value: Syntax and example
Syntax
String | Number | Object | Array | TRUE | FALSE | NULL
Example
var i = 1;
var j = "sachin";
var k = null;
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.
Use the JavaScript function JSON.parse() to convert text into a JavaScript object:
const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');
Example:
<!DOCTYPE html>
<html>
<body>
<h2>Creating an Object from a JSON String</h2>
<p id="demo"></p>
<script>
const txt = '{"name":"John", "age":30, "city":"New York"}'
const obj = JSON.parse(txt);
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;
</script>
</body>
</html>
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.
Example:
<!DOCTYPE html>
<html>
<body>
<script>
const text = '[ "Ford", "BMW", "Audi", "Fiat" ]';
const myArr = JSON.parse(text);
document.getElementById("demo").innerHTML = myArr[0];
</script>
</body>
</html>
Exceptions
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.
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:
<!DOCTYPE html>
<html>
<body>
<script>
const text = '{"name":"John", "birth":"1986-12-14", "city":"New York"}';
const obj = JSON.parse(text);
obj.birth = new Date(obj.birth);
document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth;
</script>
</body>
</html>
Or, 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.
<!DOCTYPE html>
<html>
<body>
<h2>Convert a string into a date object.</h2>
<p id="demo"></p>
<script>
const text = '{"name":"John", "birth":"1986-12-14", "city":"New York"}';
const obj = JSON.parse(text, function (key, value) {
if (key == "birth") {
return new Date(value);
} else {
return value;
}
});
document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth;
</script>
</body>
JSON.stringify( )
• A common use of JSON is to exchange data to/from a web server.
• When sending data to a web server, the data has to be a string.
• Convert a JavaScript object into a string with JSON.stringify().
<script>
const obj = {name: "John", age: 30, city: "New York"};
const myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
</script>
</body>
</html>
Stringify a JavaScript Array
• It is also possible to stringify JavaScript arrays:
const arr = ["John", "Peter", "Sally", "Jane"];
<script>
const arr = ["John", "Peter", "Sally", "Jane"];
const myJSON = JSON.stringify(arr);
document.getElementById("demo").innerHTML = myJSON;
</script>
</body>
</html>
JSON Object Literals
This is a JSON string:
'{"name":"John", "age":30, "car":null}’
<script>
const myObj = {"name":"John", "age":30, "car":null};
document.getElementById("demo").innerHTML = myObj.name;
</script>
</body>
Creating a JavaScript object by parsing a
JSON string:
<!DOCTYPE html>
<html>
<body>
<script>
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj.name;
</script>
</body>
</html>
Looping an Object
<!DOCTYPE html>
<html>
<body>
<script>
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
Description
1
2
$schema: The $schema keyword states that this schema is written according to the draft v4 specification.
Title: You will use this to give a title to your schema.
3 description: A little description of the schema.
4 type: The type keyword defines the first constraint on our JSON data: it has to be a JSON Object.
properties: Defines various keys and their value types, minimum and maximum values to be used in JSON
5
file.
6 required: This keeps a list of required properties.
7 minimum: This is the constraint to be put on the value and represents minimum acceptable value.
exclusiveMinimum: If "exclusiveMinimum" is present and has boolean value true, the instance is valid if it
8
is strictly greater than the value of "minimum".
9 maximum: This is the constraint to be put on the value and represents maximum acceptable value.
exclusiveMaximum: If "exclusiveMaximum" is present and has boolean value true, the instance is valid if it
10
is strictly lower than the value of "maximum".
multipleOf: A numeric instance is valid against "multipleOf" if the result of the division of the instance by
11
this keyword's value is an integer.
12 maxLength: The length of a string instance is defined as the maximum number of its characters.
13 minLength: The length of a string instance is defined as the minimum number of its characters.
14 pattern: A string instance is considered valid if the regular expression matches the instance successfully.
JSON - Comparison with XML
JSON and XML are human readable formats and are language independent. They
both have support for creation, reading and decoding in real world situations. We
can compare JSON with XML, based on the following factors −
Verbose
XML is more verbose than JSON, so it is faster to write JSON for programmers.
Arrays Usage
XML is used to describe the structured data, which doesn't include arrays whereas
JSON include arrays.
Parsing
JavaScript's eval method parses JSON. When applied to JSON, eval returns the
described object.
Example
JSON
{
"company": “Volkswagen”,
"name": "Vento",
"price": 800000
}
XML
<car>
<company>Volkswagen</company>
<name>Vento</name>
<price>800000</price>