0% found this document useful (0 votes)
10 views

Module 5

Uploaded by

nk493209
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Module 5

Uploaded by

nk493209
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 48

JSON

(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.

• It is primarily used to transmit data between a server and web applications.

• Web services and APIs use JSON format to provide public data.

• It can be used with modern programming languages.


Example
• The following example shows how to use JSON to store information related to books based on their topic and edition.
{
"book": [

{
"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>");

var object2 = { "language" : "C++", "author" : "E-Balagurusamy" };


document.write("<br>");
document.write("<h3>Language = " + object2.language+"</h3>");
document.write("<h3>Author = " + object2.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 −

• Data is represented in name/value pairs.

• Curly braces hold objects and each name is followed by ':'(colon), the name/value
pairs are separated by , (comma).

• Square brackets hold arrays and values are separated by ,(comma).


Example
{
"book": [

{
"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 −

• Collection of name/value pairs − This Data Structure is supported by different


programming languages.

• Ordered list of values − It includes array, list, vector or sequence etc.


DataTypes
• JSON format supports the following data types −
Sr.No
Type & Description
.
1 Number: double- precision floating-point format in JavaScript
2 String: double-quoted Unicode with backslash escaping
3 Boolean: true or false
4 Array: an ordered sequence of values
5 Value: it can be a string, a number, true or false, null etc
6 Object: an unordered collection of key:value pairs
7 Whitespace:can be used between any pair of tokens
8 Null: empty
DataTypes: Number
• It is a double precision floating-point format in JavaScript and it depends on
implementation.
• Octal and hexadecimal formats are not used.
• No NaN or Infinity is used in Number.

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

here \ / is used for Escape Character / (forward slash).


Boolean:
• This data type can be either true or false.
Syntax
var json-object-name = { string : true/false, .......}
Example:
{ "result" : true }
Array:
• It is an ordered collection of values.

• These are enclosed in square brackets which means that array begins with .[. and ends
with .]..

• The values are separated by , (comma).

• Array indexing can be started at 0 or 1.

• 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.

Text received from a web server:


'{"name":"John", "age":30, "city":"New York"}'

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>

<h2>Parsing a JSON Array.</h2>


<p>Data written as an JSON array will be parsed into a JavaScript array.</p>
<p id="demo"></p>

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

<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);
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().

Stringify a JavaScript Object


const obj = {name: "John", age: 30, city: "New York"};

Use the JavaScript function JSON.stringify() to convert it into a string.


const myJSON = JSON.stringify(obj);
The result will be a string following the JSON notation.
Example:
<!DOCTYPE html>
<html>
<body>

<h2>Create a JSON string from a JavaScript object.</h2>


<p id="demo"></p>

<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"];

Use the JavaScript function JSON.stringify() to convert it into a string.


const myJSON = JSON.stringify(arr);

The result will be a string following the JSON notation.


Example:
<!DOCTYPE html>
<html>
<body>

<h2>Create a JSON string from a JavaScript array.</h2>


<p id="demo"></p>

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

Inside the JSON string there is a JSON object literal:


{"name":"John", "age":30, "car":null}

• JSON object literals are surrounded by curly braces {}.


• JSON object literals contains key/value pairs.
• Keys and values are separated by a colon.
• Keys must be strings, and values must be a valid JSON data type:
• string
• number
• object
• array
• boolean
• null
JSON Object
• JSON object literals are surrounded by curly braces {}.
• JSON object literals contains key/value pairs.
• Keys and values are separated by a colon.
• Keys must be strings, and values must be a valid JSON data type:
• string
• number
• object
• array
• boolean
• null
• Each key/value pair is separated by a comma.
JavaScript Objects
<!DOCTYPE html>
<html>
<body>

<h2>Creating an Object from a JSON Literal</h2>


<p id="demo"></p>

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

<h2>Creating an Object Parsing JSON</h2>


<p id="demo"></p>

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

<h2>Looping Object Properties</h2>


<p id="demo"></p>

<script>
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);

let text = "";


for (const x in myObj) {
text += x + ", ";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
JSON - Schema
JSON Schema is a specification for JSON based format for defining the structure of
JSON data. It was written under IETF draft which expired in 2011. JSON Schema −

• Describes your existing data format.


• Clear, human- and machine-readable documentation.
• Complete structural validation, useful for automated testing.
• Complete structural validation, validating client-submitted data.
JSON Schema Validation Libraries
• There are several validators currently available for different programming
languages. Currently the most complete and compliant JSON Schema validator
available is JSV. Languages Libraries
C WJElement (LGPLv3)
Java json-schema-validator (LGPLv3)
.NET Json.NET (MIT)
ActionScript 3 Frigga (MIT)
Haskell aeson-schema (MIT)
Python Jsonschema
Ruby autoparse (ASL 2.0); ruby-jsonschema (MIT)
PHP php-json-schema (MIT). json-schema (Berkeley)

JavaScript Orderly (BSD); JSV; json-schema; Matic (MIT); Dojo; Persevere


(modified BSD or AFL 2.0); schema.js.
JSON Schema Example
{ "name": {
"$schema": "description": "Name of the product",
"http://json-schema.org/draft-04/schema#", "type": "string"
"title": "Product", },
"description": "A product from Acme's catalog",
"type": "object", "price": {
"type": "number",
"properties": { "minimum": 0,
"exclusiveMinimum": true
"id": { }
"description": "The unique identifier for a },
product",
"type": "integer"
"required": ["id", "name", "price"]
},
}
Sr.No. Keyword & Description

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>

You might also like