Unit 5
Unit 5
com
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5
JSON Grammar
Composite Structures
The origins of JSON stem from the ECMAScript standardization, the implementations of
the two structures are represented in the forms of the object and array.
Crockford outlines the two structural representations of JSON through a series of
syntax diagrams.
A collection begins with the use of the opening brace ({), and ends with the use of the
closing brace (}).
The content of the collection can be composedof any of the following possible three
designated paths:
The top path illustrates that the collection can remain devoid of any string/value pairs.
The middle path illustrates that our collection can be that of a single string/value pair.
The bottom path illustrates that after a single string/value pair is supplied, the
collection needn’t end but, rather, allow for any number of string/value pairs, before
607A, 6th floor, Ecstasy business park, city of joy, JSD reaching the end. Each string/value pair possessed by the collection must be delimited
road, mulund (W) | 8591065589/022-25600622 or separated from one another by way of a comma (,).
Page 1 of 30
YouTube - Abhay More | Telegram - abhay_more
Abhay More 607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
abhay_more
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5 TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5
An example of each railroad path for a collection of string/value can be viewed within
fig.
The structural characters that identify a valid JSON collection of name/value pairs have
been provided emphasis.
Examples of Valid Representations of a Collection of Key/Value Pairs, per JSON
Grammar
grammatical representation for that of an ordered list ofvalues. Here we can witness that an
ordered list begins with the use of the open bracket([) and ends with the use of the close
bracket (]).
String
JavaScript language can possess any number of Unicode characters enclosed within
either single or double quotes.
TheC programming grammar states that single quotes identify a single character, such
as a or z. A double quote, on the other hand, represents a string literal.
The values that can be held within each index are outlined by the following three“railroad”
paths:
The top path illustrates that our list can remain devoid of any value(s).
The middle path illustrates that our ordered list can possess a singularvalue.
The bottom path illustrates that the length of our list can possess anynumber of
values, which must be delimited, that is, separated, with theuse of a comma (,).
JSON Values
A JSON value can only be a representative of string, number, object, array, true, false,
and null.
Number
Page 2 of 30 Page 3 of 30
YouTube - Abhay More | Telegram - abhay_more YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622 607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5 TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5
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
<company>Volkswagen</company>
<name>Vento</name>
<price>800000</price>
</car>
JSON and XML are human readable formats and are language independent. They both Sr.No. Type & Description
have support for creation, reading and decoding in real world situations.
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5 TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5
1
3 Integer
Boolean
Digits 1-9, 0 and positive or negative
true or false
2
4 Fraction
Array
Fractions like .3, .9
an ordered sequence of values
3
5 Exponent
Value
Exponent like e, e+, e-, E, E+, E-
it can be a string, a number, true or false, null etc
Syntax
6
Object var json-object-name = { string : number_value, .......}
Page 6 of 30 Page 7 of 30
YouTube - Abhay More | Telegram - abhay_more YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622 607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5 TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5
1 Syntax
"
var json-object-name = { string : "string value", .......}
double quotation Example
Boolean
3
/ It includes true or false values.
Backspace
var obj ={name:'Amit', marks:97, distinction:true}
5 Array
f
It is an ordered collection of values.
form feed
These are enclosed in square brackets which means that array begins with .[. and ends
6 with .]..
n
9 {
u
"books":[
four hexadecimal digits
{"language":"Java","edition":"second"},
Page 8 of 30 Page 9 of 30
YouTube - Abhay More | Telegram - abhay_more YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622 607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5 TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5
{"language":"C++","lastName":"fifth"}, Example
}
null
vari=null;
The keys must be strings and should be different from each other.
Objects should be used when the key names are arbitrary strings.
Syntax if(i==1){
Example
}else{
Example showing Object −
document.write("<h1>value is null</h1>");
{ }
"id":"011A",
JSON Value
"language":"JAVA", It includes −
"price":500,
number (integer or floating point)
}
string
Whitespace boolean
It can be inserted between any pair of tokens. It can be added to make a code more readable.
array
Example shows declaration with and without whitespace −
object
Syntax
null
{string:" ",....}
Page 10 of 30 Page 11 of 30
YouTube - Abhay More | Telegram - abhay_more YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622 607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5 TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5
Syntax },
String | Number | Object | Array | TRUE | FALSE | NULL
Example
{
vari=1;
"id":"07",
var j ="sachin";
"language":"C++",
var k =null;
"edition":"second",
"author":"E.Balagurusamy"
Q3: Explain JSON in Detail.
}
Ans:
Creating JSON
]
Let's have a quick look at the basic syntax of JSON. JSON syntax is basically considered as a
Data is represented in name/value pairs. JSON supports the following two data structures −
Curly braces hold objects and each name is followed by ':'(colon), the name/value pairs Collection of name/value pairs − This Data Structure is supported by different
are separated by , (comma). programming languages.
Square brackets hold arrays and values are separated by ,(comma). Ordered list of values − It includes array, list, vector or sequence etc.
JSON objects can be created with JavaScript. Let us see the various ways of creating JSON
{
objects using JavaScript −
"book":[
Creation of an empty Object −
Creation of an object with attribute bookname with value in string, attribute price with
"edition":"third",
numeric value. Attribute is accessed by using '.' Operator −
"author":"Herbert Schildt"
Page 12 of 30 Page 13 of 30
YouTube - Abhay More | Telegram - abhay_more YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622 607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5 TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5
This is an example that shows creation of an object in javascript using JSON, save the below
code as json_object.htm −
Live Demo
<html>
The following example shows creation of an array object in javascript using JSON, save the
<title>Creating Object JSON with JavaScript</title>
below code as json_array_object.htm −
<script language = "javascript" >
Live Demo
var JSONObj = { "name" : "tutorialspoint.com", "year" : 2005 };
<html>
<head>
document.write("<h1>JSON with JavaScript example</h1>");
<title>Creation of array object in javascript using JSON</title>
document.write("<br>");
<script language = "javascript" >
document.write("<h3>Website Name = "+JSONObj.name+"</h3>");
document.writeln("<h2>JSON array object</h2>");
document.write("<h3>Year = "+JSONObj.year+"</h3>");
var books = { "Pascal" : [
</script>
{ "Name" : "Pascal Made Simple", "price" : 700 },
</head>
{ "Name" : "Guide to Pascal", "price" : 400 }],
<body>
"Scala" : [
</body>
{ "Name" : "Scala for the Impatient", "price" : 1000 },
</html>
{ "Name" : "Scala in Depth", "price" : 1300 }]
Now let's try to open Json Object using IE or any other javaScript enabled browser. It produces }
the following result −
var i = 0
Page 14 of 30 Page 15 of 30
YouTube - Abhay More | Telegram - abhay_more YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622 607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5 TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5
document.writeln("<td>"); </body>
document.writeln("</table>");
document.writeln("</td>");
document.writeln("<td>"); For parsing a JSON object, we will create an object of class JSONObject and specify a string
JSONObjectmain =reader.getJSONObject("main");
document.writeln("</tr></table>");
temperature = main.getString("temp");
</script>
</head> The method getJSONObject returns the JSON object. The method getStringreturns
Page 16 of 30 Page 17 of 30
YouTube - Abhay More | Telegram - abhay_more YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622 607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5 TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5
Apart from the these methods , there are other methods provided by this class for better Q4: Write a short note on JSON Schema with validation libraries
JSON - Schema
1
get(String name)
JSON Schema is a specification for JSON based format for defining the structure of JSON
This method just Returns the value but in the form of Object type data. It was written under IETF draft which expired in 2011. JSON Schema −
4 getInt(String name) the most complete and compliant JSON Schema validator available is JSV.
5
getLong(String name)
C WJElement (LGPLv3)
This method returns the long value specified by the key
This method returns the number of name/value mappings in this object.. .NET Json.NET (MIT)
7
names() ActionScript 3 Frigga (MIT)
This method returns an array containing the string names in this object.
Haskell aeson-schema (MIT)
Python Jsonschema
Page 18 of 30 Page 19 of 30
YouTube - Abhay More | Telegram - abhay_more YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622 607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5 TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5
"type": "number",
Orderly (BSD); JSV; json-schema; Matic (MIT); Dojo; Persevere
JavaScript
(modified BSD or AFL 2.0); schema.js.
"minimum": 0,
"exclusiveMinimum": true
JSON Schema Example
}
Given below is a basic JSON schema, which covers a classical product catalog description −
},
{
"$schema": "http://json-schema.org/draft-04/schema#",
"required": ["id", "name", "price"]
"title": "Product",
}
"description": "A product from Acme's catalog",
Let's the check various important keywords that can be used in this schema −
"type": "object",
"properties": {
1
$schema
The $schema keyword states that this schema is written according to the draft
"id": {
v4 specification.
"description": "The unique identifier for a product",
"type": "integer" 2
title
3
description
"name": {
A little description of the schema.
"description": "Name of the product",
"type": "string"
Page 20 of 30 Page 21 of 30
YouTube - Abhay More | Telegram - abhay_more YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622 607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5 TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5
4 11
type multipleOf
The type keyword defines the first constraint on our JSON data: it has to be a A numeric instance is valid against "multipleOf" if the result of the division of the
5 12
properties maxLength
Defines various keys and their value types, minimum and maximum values to The length of a string instance is defined as the maximum number of its
6 13
required minLength
This keeps a list of required properties. The length of a string instance is defined as the minimum number of its
characters.
7
minimum
14
pattern
This is the constraint to be put on the value and represents minimum acceptable
value. A string instance is considered valid if the regular expression matches the
instance successfully.
8
exclusiveMinimum
You can check a http://json-schema.org for the complete list of keywords that can be used in
If "exclusiveMinimum" is present and has boolean value true, the instance is
defining a JSON schema. The above schema can be used to test the validity of the following
valid if it is strictly greater than the value of "minimum".
JSON code −
9
maximum [
This is the constraint to be put on the value and represents maximum acceptable {
value. "id": 2,
Page 22 of 30 Page 23 of 30
YouTube - Abhay More | Telegram - abhay_more YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622 607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5 TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5
{ Syntax
string json_encode( $value [, $options = 0 ] )
"id": 3,
Parameters
"name": "A blue mouse",
value − The value being encoded. This function only works with UTF-8 encoded data.
"price": 25.50,
options − This optional value is a bitmask consisting of JSON_HEX_QUOT,
}
JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK,
Example
Q5: Explain JSON with PHP, HTML and Python
The following example shows how to convert an array into JSON with PHP −
Ans:
<?php
JSON with PHP
$arr=array('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
This chapter covers how to encode and decode JSON objects using PHP programming
echo json_encode($arr);
language. Let's start with preparing the environment to start our programming with PHP
?>
for JSON.
Environment
While executing, this will produce the following result −
As of PHP 5.2.0, the JSON extension is bundled and compiled into PHP by default.
{"a":1,"b":2,"c":3,"d":4,"e":5}
JSON Functions
The following example shows how the PHP objects can be converted into JSON −
Function Libraries
<?php
PHP json_encode() function is used for encoding JSON in PHP. This function returns the
$e =newEmp();
JSON representation of a value on success or FALSE on failure.
Page 24 of 30 Page 25 of 30
YouTube - Abhay More | Telegram - abhay_more YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622 607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5 TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5
$e->name ="sachin";
json_string − It is an encoded string which must be UTF-8 encoded data. JSON can very easily be translated into JavaScript.
assoc − It is a boolean type parameter, when set to TRUE, returned objects will be JavaScript can be used to make HTMl in your web pages.
converted into associative arrays. Make an HTML Table with data Received as JSON:
depth − It is an integer type parameter which specifies recursion depth <!DOCTYPE html>
<html>
options − It is an integer type bitmask of JSON decode, JSON_BIGINT_AS_STRING is <body>
The following example shows how PHP can be used to decode JSON objects − <script>
var obj, dbParam, xmlhttp, myObj, x, txt = "";
<?php obj = { table: "customers", limit: 20 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
$json ='{"a":1,"b":2,"c":3,"d":4,"e":5}';
xmlhttp.onreadystatechange = function() {
Page 26 of 30 Page 27 of 30
YouTube - Abhay More | Telegram - abhay_more YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622 607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5 TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5
</body> Before you start with encoding and decoding JSON using Python, you need to install any of
</html>
the JSON modules available. For this tutorial we have downloaded and installed Demjson as
follows −
Make a table based on JSON data. $tar xvfz demjson-1.6.tar.gz
$cd demjson-1.6
AlfredsFutterkiste $python setup.py install
Ana Trujillo Emparedados y helados
JSON Functions
Antonio Moreno Taqueria
Around the Horn Function Libraries
Berglundssnabbkop
Blauer See Delikatessen
encode Encodes the Python object into a JSON string representation.
Blondel pere et fils
BolidoComidaspreparadas
Bon app' decode Decodes a JSON-encoded string into a Python object.
Bottom-Dollar Marketse
B's Beverages
Cactus Comidas para llevar Encoding JSON in Python (encode)
Centro comercial Moctezuma Python encode() function encodes the Python object into a JSON string representation.
Chop-suey Chinese
Syntax
Comercio Mineiro
Consolidated Holdings demjson.encode(self, obj, nest_level=0)
DrachenblutDelikatessend Example
Du monde entier
The following example shows arrays under JSON with Python.
Eastern Connection
Ernst Handel
#!/usr/bin/python
importdemjson
Page 28 of 30 Page 29 of 30
YouTube - Abhay More | Telegram - abhay_more YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622 607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
data =[{'a':1,'b':2,'c':3,'d':4,'e':5}]
json =demjson.encode(data)
print json
[{"a":1,"b":2,"c":3,"d":4,"e":5}]
Python can use demjson.decode() function for decoding JSON. This function returns the
Syntax
demjson.decode(self, txt)
Example
The following example shows how Python can be used to decode JSON objects.
#!/usr/bin/python
importdemjson
json ='{"a":1,"b":2,"c":3,"d":4,"e":5}';
text =demjson.decode(json)
print text
Page 30 of 30
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622