[go: up one dir, main page]

0% found this document useful (0 votes)
4 views8 pages

Unit 5

Uploaded by

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

Unit 5

Uploaded by

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

www.acuityeducare.

com
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5

Q1: What is JSON?


Ans:
Acuity Educare  The JavaScript Object Notation data format, or JSON for short, is derived from the
literals of the JavaScript programming language. This makes JSON a subset of the
JavaScript language.
 As a subset, JSON does not possess any additional features that the JavaScript
language itself does not already possess. Although JSON is a subset of a programming
NGT language, it itself is not a programming language but, in fact, a data interchange
format.
 JSON is known as the data interchange standard, which subtextually implies that it can
SEM : V be used as the data format wherever the exchange of data occurs.
 A data exchange can occur between both browser and server and even server to
server, for that matter. Of course, these are not the only possible means to exchange
SEM V: UNIT 5 JSON, and to leave it at those two would be rather limiting.

JSON Grammar

 JSON, in a nutshell, is a textual representation defined by a small set of governing


rules in which data is structured.
 The JSON specification states that data can be structured in either of the two following
compositions:

1. A collection of name/value pairs


2. An ordered list of values

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

//Empty Collection Set


{};
//Single string/value pair
{"abc":"123"};
//Multiple string/value pairs
{"captainsLog":"starDate 9522.6","message":"I've never trusted
Klingons, and I never will."};

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

 A number in JSON is the arrangement of base10 literals, in combination with


mathematical notation to define a real number literal.

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

Individual examples of XML and JSON −


 JSON
 The first thing to note is that the numbers grammar does not begin or end with any
particular symbolic representation, as our earlier object, array, and string examples {
did.
"company": Volkswagen,
JSON Tokens
"name": "Vento",
 JSON is nothing more than a sequence of Unicode characters. However, the JSON
grammar standardizes which Unicode characters or “tokens” define valid JSON, in
"price": 800000
addition to demarcating the values contained within.
 When regarding the interchange of JSON and the many languages that do not natively
possess Objects and Arrays, the tokens that make up the JSON text are all that is }
required to interpret if any collections or ordered lists exist and apply all values in a
manner required of that language.  XML

This is accomplished with six structural characters:


<car>

<company>Volkswagen</company>

<name>Vento</name>

<price>800000</price>

</car>

Q2: Write a short note on json Data types.


Ans:
Json vs XML JSON format supports the following data types −

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

We can compare JSON with XML, based on the following factors-


 Verbose
Page 4 of 30 Page 5 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  Octal and hexadecimal formats are not used.


Number
 No NaN or Infinity is used in Number.
double- precision floating-point format in JavaScript
The following table shows the number types −
2
String Sr.No. Type & Description

double-quoted Unicode with backslash escaping

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, .......}

an unordered collection of key:value pairs Example

Example showing Number Datatype, value should not be quoted −


7
Whitespace
var obj ={marks:97}
can be used between any pair of tokens
String

8  It is a sequence of zero or more double quoted Unicode characters with backslash


null
escaping.
empty
 Character is a single character string i.e. a string with length 1.
Number
The table shows various special characters that you can use in strings of a JSON document −
 It is a double precision floating-point format in JavaScript and it depends on
Sr.No. Type & Description
implementation.

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

Example showing String Datatype −


2
\
var obj ={name:'Amit'}
Backslash

Boolean
3
/ It includes true or false values.

forward slash Syntax


var json-object-name = { string : true/false, .......}
4
B Example

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

new line  The values are separated by , (comma).

 Array indexing can be started at 0 or 1.


7
r
 Arrays should be used when the key names are sequential integers.
carriage return Syntax
[ value, .......]
8
t
Example

horizontal tab Example showing array containing multiple objects −

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

{"language":"C","lastName":"third"} var obj1 ={"name":"Sachin Tendulkar"}

] var obj2 ={"name":"SauravGanguly"}

}
null

Object It means empty type.

 It is an unordered set of name/value pairs. Syntax


null
 Objects are enclosed in curly braces that is, it starts with '{' and ends with '}'.
Example
 Each name is followed by ':'(colon) and the key/value pairs are separated by , (comma).

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

{ string : value, .......} document.write("<h1>value is 1</h1>");

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

subset of JavaScript syntax; it includes the following − }

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

Below is a simple example − JSON- Object Creation

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 −

var JSONObj = {};


{

"id":"01",  Creation of a new Object −

"language":"Java", var JSONObj = new 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

var JSONObj = { "bookname ":"VB BLACK BOOK", "price":500 };

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>

<head> Creating Array Objects

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

document.writeln("<table border = '2'><tr>");

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

for(i = 0;i<books.Pascal.length;i++) { <body>

document.writeln("<td>"); </body>

document.writeln("<table border = '1' width = 100 >"); </html>

document.writeln("<tr><td><b>Name</b></td><td width = 50>" +


Now let's try to open Json Array Object using IE or any other javaScript enabled browser. It
books.Pascal[i].Name+"</td></tr>");
produces the following result −
document.writeln("<tr><td><b>Price</b></td><td width = 50>" + books.Pascal[i].price
+"</td></tr>");

document.writeln("</table>");

document.writeln("</td>");

for(i = 0;i<books.Scala.length;i++) { Parsing JSON

document.writeln("<td>"); For parsing a JSON object, we will create an object of class JSONObject and specify a string

containing JSON data to it. Its syntax is −


document.writeln("<table border = '1' width = 100 >");
String in;
document.writeln("<tr><td><b>Name</b></td><td width = 50>" + JSONObject reader = new JSONObject(in);
books.Scala[i].Name+"</td></tr>");
The last step is to parse the JSON. A JSON file consist of different object with different
document.writeln("<tr><td><b>Price</b></td><td width = 50>" +
key/value pair e.t.c. So JSONObject has a separate function for parsing each of the component
books.Scala[i].price+"</td></tr>");
of JSON file. Its syntax is given below −
document.writeln("</table>");
JSONObjectsys =reader.getJSONObject("sys");
document.writeln("</td>");
country = sys.getString("country");
}

JSONObjectmain =reader.getJSONObject("main");
document.writeln("</tr></table>");
temperature = main.getString("temp");
</script>

</head>  The method getJSONObject returns the JSON object. The method getStringreturns

the string value of the specified key.

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

parsing JSON files. These methods are listed below −


Ans:
Sr.No Method & description
JSON - Data Interchange:

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 −

2  Describes your existing data format.


getBoolean(String name)
 Clear, human- and machine-readable documentation.
This method returns the boolean value specified by the key
 Complete structural validation, useful for automated testing.

3  Complete structural validation, validating client-submitted data.


getDouble(String name)
JSON Schema Validation Libraries
This method returns the double value specified by the key
There are several validators currently available for different programming languages. Currently

4 getInt(String name) the most complete and compliant JSON Schema validator available is JSV.

This method returns the integer value specified by the key


Languages Libraries

5
getLong(String name)
C WJElement (LGPLv3)
This method returns the long value specified by the key

Java json-schema-validator (LGPLv3)


6
length()

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

Ruby autoparse (ASL 2.0); ruby-jsonschema (MIT) },

PHP php-json-schema (MIT). json-schema (Berkeley)


"price": {

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

Sr.No. Keyword & Description

"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

}, You will use this to give a title to your schema.

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

JSON Object. instance by this keyword's value is an integer.

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

be used in JSON file. characters.

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,

10 "name": "An ice sculpture",


exclusiveMaximum
"price": 12.50,
If "exclusiveMaximum" is present and has boolean value true, the instance is
},
valid if it is strictly lower than the value of "maximum".

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,

] JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT.

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

json_encode Returns the JSON representation of a value. classEmp{

public $name ="";


json_decode Decodes a JSON string.
public $hobbies ="";

public $birthdate ="";


json_last_error Returns the last error occurred.
}

Encoding JSON in PHP (json_encode)

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

$e->hobbies ="sports"; var_dump(json_decode($json));

$e->birthdate =date('m/d/Y h:i:s a',"8/5/1974 12:20:03 p"); var_dump(json_decode($json,true));

$e->birthdate =date('m/d/Y h:i:s a',strtotime("8/5/1974 12:20:03")); ?>

While executing, it will produce the following result −


echo json_encode($e);
object(stdClass)#1 (5) {
["a"] =>int(1)
?> ["b"] =>int(2)
["c"] =>int(3)
["d"] =>int(4)
While executing, this will produce the following result −
["e"] =>int(5)
}
{"name":"sachin","hobbies":"sports","birthdate":"08\/05\/1974 12:20:03 pm"}
array(5) {
Decoding JSON in PHP (json_decode)
["a"] =>int(1)
 PHP json_decode() function is used for decoding JSON in PHP. This function returns the ["b"] =>int(2)
["c"] =>int(3)
value decoded from json to appropriate PHP type. ["d"] =>int(4)
["e"] =>int(5)
Syntax }
mixed json_decode ($json [,$assoc = false [, $depth = 512 [, $options = 0 ]]])

Paramaters JSON with HTML

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

supported. <h2>Make a table based on JSON data.</h2>

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

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

if (this.readyState == 4 &&this.status == 200) {


myObj = JSON.parse(this.responseText);
txt += "<table border='1'>"
for (x in myObj) {
txt += "<tr><td>" + myObj[x].name + "</td></tr>";
} JSON with Python
txt += "</table>"
document.getElementById("demo").innerHTML = txt;
}  This chapter covers how to encode and decode JSON objects using Python programming
}; language. Let's start with preparing the environment to start our programming with
xmlhttp.open("POST", "json_demo_db_post.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); Python for JSON.
xmlhttp.send("x=" + dbParam);
</script> Environment

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

TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V NGT: UNIT5

data =[{'a':1,'b':2,'c':3,'d':4,'e':5}]

json =demjson.encode(data)

print json

While executing, this will produce the following result −

[{"a":1,"b":2,"c":3,"d":4,"e":5}]

Decoding JSON in Python (decode)

 Python can use demjson.decode() function for decoding JSON. This function returns the

value decoded from json to an appropriate Python type.

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

On executing, it will produce the following result −

{u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4}

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

You might also like