JSON or JavaScript Object Notation is a lightweight text-based open standard designed JSON or JavaScript Object Notation is a lightweight text-based open standard designed for human-readable data interchange. The JSON format was originally specified by for human-readable data interchange. The JSON format was originally specified by Douglas Crockford, and is described in RFC 4627. The official Internet media type for Douglas Crockford, and is described in RFC 4627. The official Internet media type for JSON is application/json. The JSON filename extension is .json.
JSON is application/json. The JSON filename extension is .json.
This tutorial will help you understand JSON and its use within various programming This tutorial will help you understand JSON and its use within various programming languages such as PHP, PERL, Python, Ruby, Java, etc.
languages such as PHP, PERL, Python, Ruby, Java, etc.
Audience
Audience
This tutorial has been designed to help beginners understand the basic functionality of This tutorial has been designed to help beginners understand the basic functionality of JavaScript Object Notation (JSON) to develop the data interchange format. After JavaScript Object Notation (JSON) to develop the data interchange format. After completing this tutorial, you will have a good understanding of JSON and how to use it completing this tutorial, you will have a good understanding of JSON and how to use it with JavaScript, Ajax, Perl, etc.
with JavaScript, Ajax, Perl, etc.
Prerequisites
Prerequisites
Before proceeding with this tutorial, you should have a basic understanding of the web Before proceeding with this tutorial, you should have a basic understanding of the web application
application’s’s work over HTTP and we assume that you have a basic knowledge of work over HTTP and we assume that you have a basic knowledge of
JavaScript. JavaScript.
Copyright & Disclaimer
Copyright & Disclaimer
Copyright 2017 by Tutorials Point (I) Pvt. Ltd. Copyright 2017 by Tutorials Point (I) Pvt. Ltd.
All the content and graphics published in this e-book are the property of Tutorials Point All the content and graphics published in this e-book are the property of Tutorials Point (I) Pvt. Ltd.
(I) Pvt. Ltd. The user of The user of this e-book is prohibited to this e-book is prohibited to reuse, retain, copy, reuse, retain, copy, distribute ordistribute or republish any contents or a part of contents of this e-book in any manner without written republish any contents or a part of contents of this e-book in any manner without written consent of the publisher.
consent of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely We strive to update the contents of our website and tutorials as timely and as precisely as possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) as possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our website or its contents including this tutorial. If you discover any errors on our our website or its contents including this tutorial. If you discover any errors on our website or in this tutorial, please notify us at
About
About the the Tutorial ... Tutorial ... ii
Audience ... i
Audience ... i
Prerequisites ... i
Prerequisites ... i
Copyright Copyright & & Disclaimer ... Disclaimer ... ii
Table Table of Contents ... iiof Contents ... ii
Uses of Uses of JSON ... JSON ... 11 Characteristics Characteristics of of JSON JSON ... ... 11 Simple Exam Simple Example in ple in JSON ... JSON ... 11 Number ... 5 Number ... 5 String String ... ... 66 Boolean ... 7 Boolean ... 7 Array ... 7 Array ... 7 Object Object ... ... 88 Whitespace Whitespace ... ... 88 null ... 9 null ... 9 JSON
JSON Value ... Value ... 99
Creating Simple
Creating Simple Objects ... Objects ... 1010 Creating Array
Creating Array Objects ... Objects ... 1111
JSON ─ OVERVIEW JSON ─ OVERVIEW
JSON
JSON ─ ─ SYNT SYNT
JSON
JSON ─ ─ D D T T TYPESTYPES
JSON ─ OBJECTS
JSON Schema Va
JSON Schema Va lidation Librarlidation Librar ies ... ies ... 1313 JSON Schema
JSON Schema Example ... 14Example ... 14
Environment
Environment ... ... 1818 JSON Functions
JSON Functions ... ... 1818 Encoding JSON in
Encoding JSON in PHP (json_encode) ... PHP (json_encode) ... 1818 Decoding JSON
Decoding JSON in PHP in PHP (json_decode) (json_decode) ... ... 1919
Environment
Environment ... ... 2121 JSON Functions
JSON Functions ... ... 2121 Encoding JSON in Perl
Encoding JSON in Perl (encode_json) ... (encode_json) ... 2222 Decoding JSON
Decoding JSON in Perl in Perl (decode_json) ... (decode_json) ... 2323
Environment
Environment ... ... 2525 JSON Functions
JSON Functions ... ... 2525 Encoding JSON
Encoding JSON in Python in Python (encode) (encode) ... ... 2525 Decoding JSON in
Decoding JSON in Python (decode) Python (decode) ... ... 2626
Environment
Environment ... ... 2727 Parsing JSON
Parsing JSON using Ruby ... 27using Ruby ... 27
JSON
JSON ─ ─ COMP COMP RISON RISON WIWITH TH XML XML 1717
JSON ─ JSON WITH PHP
JSON ─ JSON WITH PHP 1818
JSON ─ JSON WITH PER
JSON ─ JSON WITH PERL L 2121
JSON ─ JSON WITH PYT
Environment
Environment ... ... 2929 Mapping between
Mapping between JSON and Java JSON and Java entities ... entities ... 2929 Encoding JSON
Encoding JSON in Java ... 30in Java ... 30 Decoding JSON
Decoding JSON in in Java Java ... ... 3131
12
JSON or JavaScript Object Notation is a lightweight text-based open standard designed JSON or JavaScript Object Notation is a lightweight text-based open standard designed for human-readable data interchange. Conventions used by JSON are known to for human-readable data interchange. Conventions used by JSON are known to programmers, which include C, C++, Java, Python, Perl, etc.
programmers, which include C, C++, Java, Python, Perl, etc.
JSON stands for JavaScript Object Notation.JSON stands for JavaScript Object Notation.
The format was specified by Douglas Crockford.The format was specified by Douglas Crockford.
It was designed for human-readable data interchange.It was designed for human-readable data interchange.
It has been extended from the JavaScript scripting language.It has been extended from the JavaScript scripting language.
The filename extension isThe filename extension is .json.json..
JSON Internet Media type isJSON Internet Media type is application/jsonapplication/json..
The Uniform Type Identifier is public.json.The Uniform Type Identifier is public.json.
Uses of JSON
Uses of JSON
It is used while writing JavaScript based applications that includes browserIt is used while writing JavaScript based applications that includes browser
extensions and websites. extensions and websites.
JSON format is used for serializing and transmitting structured data over networkJSON format is used for serializing and transmitting structured data over network
connection. connection.
It is primarily used to transmit data between a It is primarily used to transmit data between a server and web applications.server and web applications.
Web services and APIs use JSON format to provide public data.Web services and APIs use JSON format to provide public data.
It can be used with modern programming languages.It can be used with modern programming languages.
Characteristics of JSON
Characteristics of JSON
JSON is easy to read and write.JSON is easy to read and write.
It is a lightweight text-based interchange format.It is a lightweight text-based interchange format.
JSON is language independent.JSON is language independent.
Simple Example in JSON
Simple Example in JSON
The following example shows how to use JSON to store information related to books The following example shows how to use JSON to store information related to books based on their topic and edition.
based on their topic and edition.
{ { "book": [ "book": [ { {
1. JSON
"id":"01", "id":"01", "language": "Java", "language": "Java", "edition": "third", "edition": "third",
"author": "Herbert Schildt" "author": "Herbert Schildt" }, }, { { "id":"07", "id":"07", "language": "C++", "language": "C++", "edition": "second" "edition": "second" "author":
"author": "E.Balagurusa"E.Balagurusamy"my" }]
}] }
}
After understanding the above program, we will try another example. Let's save the After understanding the above program, we will try another example. Let's save the below code as
below code as json.htm json.htm::
<html> <html> <head> <head>
<title>JSON
<title>JSON example</title>example</title> <script language="javascript" > <script language="javascript" >
var object1
var object1 = { "lang= { "language" : "Java", uage" : "Java", "author" "author" : "herbert sc: "herbert schildt" };hildt" }; document.write("<
document.write("<h1>JSON with h1>JSON with JavaScript example</h1>");JavaScript example</h1>"); document.write("<br>");
document.write("<br>"); document.write("<
document.write("<h3>Language = " h3>Language = " + object1.language+"</h3>");+ object1.language+"</h3>"); document.write("<
document.write("<h3>Author = h3>Author = " " + object1.author+"</h3>");+ object1.author+"</h3>");
var object2
var object2 = { "= { "language" : language" : "C++", "au"C++", "author" thor" : "E-Bala: "E-Balagurusamy" };gurusamy" }; document.write("<br>");
document.write("<br>"); document.write("<
document.write("<h3>Language = " h3>Language = " + object2.language+"</h3>");+ object2.language+"</h3>"); document.write("<
document.write("<h3>Author = h3>Author = " " + object2.author+"</h3>");+ object2.author+"</h3>");
document.write("<
document.write("<hr hr />");/>"); document.write(ob
document.write(object2.language + " programming language can be studied " ject2.language + " programming language can be studied " ++ "from book written by "
"from book written by " + object2.author);+ object2.author); document.write("<
</script> </script> </head> </head> <body> <body> </body> </body> </html> </html>
Now let's try to open
Now let's try to open json.htm json.htm using IE or any other javascript enabled browser thatusing IE or any other javascript enabled browser that produces the following result:
produces the following result:
You can refer to
Let's have a quick look at the basic syntax of JSON. JSON syntax is basically considered Let's have a quick look at the basic syntax of JSON. JSON syntax is basically considered as a subset of JavaScript syntax; it
as a subset of JavaScript syntax; it includes the following:includes the following:
Data is represented in name/value pairs.Data is represented in name/value pairs.
Curly braces hold objects and each name is followed by ':'(colon), theCurly braces hold objects and each name is followed by ':'(colon), the
name/value pairs are separated by , (comma). name/value pairs are separated by , (comma).
Square brackets hold arrays and values are separated by ,(comma).Square brackets hold arrays and values are separated by ,(comma).
Below is a simple example: Below is a simple example:
{ { "book": [ "book": [ { { "id":"01", "id":"01", "language": "Java", "language": "Java", "edition": "third", "edition": "third",
"author": "Herbert Schildt" "author": "Herbert Schildt" }, }, { { "id":"07", "id":"07", "language": "C++", "language": "C++", "edition": "second" "edition": "second" "author": "E.Balagurusamy" "author": "E.Balagurusamy" }] }] } }
JSON supports the following two data structures: JSON supports the following two data structures:
Collection of name/value pairs:Collection of name/value pairs: This Data Structure is supported by different This Data Structure is supported by different
programming languages. programming languages.
Ordered list of values:Ordered list of values: It includes array, list, vector or sequence etc. It includes array, list, vector or sequence etc.
2. JSON
JSON format supports the following data types: JSON format supports the following data types:
Type Description
Type Description
Number
Number double- double- precision precision floating-point floating-point format format in in JavaScriptJavaScript
String
String double-quoted double-quoted Unicode Unicode with with backslash backslash escapingescaping
Boolean
Boolean true true or or falsefalse
Array
Array an an ordered ordered sequence sequence of of valuesvalues
Value
Value it it can can be be a a string, string, a a number, number, true true or or false, false, null null etcetc
Object
Object an an unordered unordered collection collection of of key:value key:value pairspairs
Whitespace
Whitespace can can be be used used between between any any pair pair of of tokenstokens
null empty
null empty
Number
Number
It is a double precision floating-point format in JavaScript and it depends onIt is a double precision floating-point format in JavaScript and it depends on
implementation. implementation.
Octal and hexadecimal formats are not used.Octal and hexadecimal formats are not used.
No NaN or Infinity is used in Number.No NaN or Infinity is used in Number.
The following table shows the number types: The following table shows the number types:
Type Description
Type Description
Integer
Integer Digits Digits 1-9, 1-9, 0 0 and and positive positive or or negativenegative
Fraction
Fraction Fractions Fractions like like .3, .3, .9.9
Exponent
Exponent Exponent Exponent like like e, e, e+, e+, e-,E, e-,E, E+, E+, E-
E-3. JSON
Syntax
Syntax
var json-object-name = {"string" : number_value, ...} var json-object-name = {"string" : number_value, ...}
Example
Example
Example showing Number Datatype, value should not be quoted: Example showing Number Datatype, value should not be quoted:
var obj = {"marks": 97} var obj = {"marks": 97}
String
String
It is a sequence of zero or more double quoted Unicode characters with backslashIt is a sequence of zero or more double quoted Unicode characters with backslash
escaping. escaping.
Character is a single character string iCharacter is a single character string i .e. a string with length 1..e. a string with length 1.
The table shows various special characters that you can use in strings of a JSON The table shows various special characters that you can use in strings of a JSON document:
document:
Type Description
Type Description
"
" double double quotationquotation
\ backslash
\ backslash
/
/ forward slashforward slash
b backspace
b backspace
f
f form form feedfeed
n
n new new lineline
r
r carriage carriage returnreturn
t
t horizontal horizontal tabtab
u
u four four hexadecimal hexadecimal digitsdigits
Syntax
Syntax
var json-object-name = { string
Example
Example
Example showing String Datatype: Example showing String Datatype:
var obj = {"name": "Amit"} var obj = {"name": "Amit"}
Boolean
Boolean
It includes true or false values. It includes true or false values.
Syntax
Syntax
var json-object-name = { string
var json-object-name = { string : true/false, ...}: true/false, ...}
Example
Example
var obj =
var obj = {"name": "Amit", "marks": 97, "distinction": true}{"name": "Amit", "marks": 97, "distinction": true}
Array
Array
It is an ordered collection of values.It is an ordered collection of values.
These are enclosed in square brackets which means that array begins with .[. andThese are enclosed in square brackets which means that array begins with .[. and
ends with .].. ends with .]..
The values are separated by , (comma).The values are separated by , (comma).
Array indexing can be started at 0 or 1.Array indexing can be started at 0 or 1.
Arrays should be used when the key names are sequential integers.Arrays should be used when the key names are sequential integers.
Syntax
Syntax
[ value, ...] [ value, ...]Example
Example
Example showing array containing multiple objects: Example showing array containing multiple objects:
{ { "books": [ "books": [ { "language":"Java" , "edition":"second" }, { "language":"Java" , "edition":"second" }, { "language":"C++" , "lastName":"fifth" }, { "language":"C++" , "lastName":"fifth" }, { "language":"C" , "lastName":"third" } { "language":"C" , "lastName":"third" } ] ] } }
Object
Object
It is an unordered set of name/value pairs.It is an unordered set of name/value pairs.
Objects are enclosed in curly braces that is, it starts with '{' and ends with '}'.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 ,Each name is followed by ':'(colon) and the key/value pairs are separated by ,
(comma). (comma).
The keys must be strings and should be different from each other.The keys must be strings and should be different from each other.
Objects should be used when the key names are arbitrary strings.Objects should be used when the key names are arbitrary strings.
Syntax
Syntax
{ string : value, ...} { string : value, ...}Example
Example
Example showing Object: Example showing Object:
{ { "id": "011A", "id": "011A", "language": "JAVA", "language": "JAVA", "price": 500, "price": 500, } }
Whitespace
Whitespace
It can be inserted between any pair of tokens. It can be added to make a code more 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:
readable. Example shows declaration with and without whitespace:
Syntax
Syntax
{string: {string: " " ",....}",....}Example
Example
var obj1 =var obj1 = {"name": "Sachin Tendulkar"}{"name": "Sachin Tendulkar"} var obj2 =
null
null
It means empty type. It means empty type.
Syntax
Syntax
null nullExample
Example
var i = null; var i = null; if(i==1) if(i==1) { { document.write(" document.write("<h1>value is <h1>value is 1</h1>");1</h1>"); } } else else { { document.write("document.write("<h1>value is <h1>value is null</h1>");null</h1>"); }
}
JSON
JSON V
Value
alue
It includes: It includes:
number (integer or floating point)number (integer or floating point) stringstring booleanboolean arrayarray objectobject nullnull
Syntax
Syntax
String | Number | Object | Array | TRUE
String | Number | Object | Array | TRUE | FALSE | NULL| FALSE | NULL
Example
Example
var i = 1; var i = 1; var j = "sachin"; var j = "sachin"; var k = null; var k = null;Creating Simple Objects
Creating Simple Objects
JSON objects can be created with JavaScript. Let us see the various ways of creating JSON objects can be created with JavaScript. Let us see the various ways of creating JSON objects using JavaScript:
JSON objects using JavaScript:
Creation of an empty Object:Creation of an empty Object:
var JSONObj = {}; var JSONObj = {};
Creation of a new Object:Creation of a new Object:
var JSONObj = new
var JSONObj = new Object();Object();
Creation of an object with attributeCreation of an object with attribute booknamebookname with value in string,with value in string,
attribute
attribute priceprice with numeric value. Attribute is accessed by using '.' Operator:with numeric value. Attribute is accessed by using '.' Operator:
var JSONObj = {
var JSONObj = { "bookname ":"VB BLACK BOOK", "price":500 };"bookname ":"VB BLACK BOOK", "price":500 };
This is an example that shows creation of an object in javascript using JSON, save the This is an example that shows creation of an object in javascript using JSON, save the below code as
below code as json_object.htm json_object.htm::
<html> <html> <head> <head>
<title>Creating Object JSON with JavaScript</title> <title>Creating Object JSON with JavaScript</title> <script language="javascript" >
<script language="javascript" >
var JSONObj
var JSONObj = { "= { "name" : name" : "tutorialspoin"tutorialspoint.com", "year" t.com", "year" : 2005 }: 2005 };; document.write("<
document.write("<h1>JSON with h1>JSON with JavaScript example</h1>");JavaScript example</h1>"); document.write("<br>");
document.write("<br>"); document.write("<
document.write("<h3>Website h3>Website Name="+JSONObj.name+"<Name="+JSONObj.name+"</h3>");/h3>"); document.write("<h3>Year="+JSONObj.year+"</h3>"); document.write("<h3>Year="+JSONObj.year+"</h3>"); </script> </script> </head> </head> <body> <body> </body> </body> </html> </html>
4. JSON
Now let's try to open
Now let's try to open json_object.htm json_object.htm using IE or any other javascript enabled browser.using IE or any other javascript enabled browser. It produces the following result:
It produces the following result:
Creating Array Objects
Creating Array Objects
The following example shows creation of an array object in javascript using JSON, save The following example shows creation of an array object in javascript using JSON, save the below code as
the below code as json_array_object json_array_object.htm.htm::
<html> <html> <head> <head>
<title>Creation of array object in javascript using JSON</title> <title>Creation of array object in javascript using JSON</title> <script language="javascript" >
<script language="javascript" >
document.writeln("<
document.writeln("<h2>JSON array h2>JSON array object</h2>");object</h2>");
var books = { "Pascal" : [ var books = { "Pascal" : [
{ "Name"
{ "Name" : "Pasc: "Pascal Made al Made Simple", "priSimple", "price" : 70ce" : 700 },0 }, { "Name
{ "Name" " : "Gui: "Guide to de to Pascal", "pPascal", "price" : rice" : 400 }400 } ],
],
"Scala" "Scala" : : [[
{ "Name"
{ "Name" : "Scal: "Scala for ta for the Impatient", he Impatient", "price" : "price" : 1000 },1000 }, { "Name
{ "Name" " : "Sca: "Scala in la in Depth", "prDepth", "price" : ice" : 1300 }1300 } ] ] } } var i = 0 var i = 0 document.writeln("<
document.writeln("<table table border='2'><tr>border='2'><tr>");"); for(i=0;i<books.Pascal.length;i++) for(i=0;i<books.Pascal.length;i++) { { document.writeln("<td>"); document.writeln("<td>");
document.writeln
document.writeln("<table border='1' width=100 ("<table border='1' width=100 >");>"); document.writeln
document.writeln("<tr><td><b>Nam("<tr><td><b>Name</b></td><td e</b></td><td width=50>"width=50>" +
+ books.Pascal[i].Nbooks.Pascal[i].Name+"</td></tr>");ame+"</td></tr>"); document.writeln
document.writeln("<tr><td><b>Pri("<tr><td><b>Price</b></td><td ce</b></td><td width=50>"width=50>" +
+ books.Pascal[i].pbooks.Pascal[i].price rice +"</td></tr>");+"</td></tr>"); document.writeln("</table>"); document.writeln("</table>"); document.writeln("</td>"); document.writeln("</td>"); } } for(i=0;i<books.Scala.length;i++) for(i=0;i<books.Scala.length;i++) { { document.writeln("<td>"); document.writeln("<td>"); document.writeln
document.writeln("<table border='1' width=100 ("<table border='1' width=100 >");>"); document.writeln
document.writeln("<tr><td><b>Nam("<tr><td><b>Name</b></td><td e</b></td><td width=50>"width=50>" +
+ books.Scala[i].Nabooks.Scala[i].Name+"</td></tr>");me+"</td></tr>"); document.writeln
document.writeln("<tr><td><b>Pri("<tr><td><b>Price</b></td><td ce</b></td><td width=50>"width=50>" +
+ books.Scala[i].prbooks.Scala[i].price+"</td></tr>");ice+"</td></tr>"); document.writeln("</table>"); document.writeln("</table>"); document.writeln("</td>"); document.writeln("</td>"); } } document.writeln("</tr></table>"); document.writeln("</tr></table>"); </script> </script> </head> </head> <body> <body> </body> </body> </html> </html>
Now let's try to open
Now let's try to open json_array_object.htm json_array_object.htm using IE or any other javascript enabledusing IE or any other javascript enabled browser. It produces the following result:
JSON Schema is a specification for JSON based format for defining the structure of JSON 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 Sch
data. It was written under IETF draft which expired in 2011. JSON Sch ema:ema:
Describes your existing data format.Describes your existing data format.
Clear, human- and machine-readable documentation.Clear, human- and machine-readable documentation.
Complete structural validation, useful for automated testing.Complete structural validation, useful for automated testing.
Complete structural validation, validating client-submitted data.Complete structural validation, validating client-submitted data.
JSON Schema Validation Libraries
JSON Schema Validation Libraries
There are several validators currently available for different programming languages. There are several validators currently available for different programming languages. Currently the most complete and compliant JSON Schema validator available is JSV. Currently the most complete and compliant JSON Schema validator available is JSV.
Languages Libraries
Languages Libraries
C
C WJElement WJElement (LGPLv3)(LGPLv3)
Java
Java json-schema-validator json-schema-validator (LGPLv3)(LGPLv3)
.NET
.NET Json.NET Json.NET (MIT)(MIT)
ActionScript
ActionScript 3 3 Frigga Frigga (MIT)(MIT)
Haskell
Haskell aeson-schema aeson-schema (MIT)(MIT)
Python Jsonschema
Python Jsonschema
Ruby
Ruby autoparse autoparse (ASL (ASL 2.0); 2.0); ruby-jsonschema ruby-jsonschema (MIT)(MIT)
PHP
PHP php-json-schema php-json-schema (MIT). (MIT). json-schema json-schema (Berkeley)(Berkeley)
JavaScript
JavaScript Orderly (BSD); JSV; json-schema; Matic (MIT); Dojo; PersevereOrderly (BSD); JSV; json-schema; Matic (MIT); Dojo; Persevere (modified BSD or AFL 2.0); schema.js.
(modified BSD or AFL 2.0); schema.js.
5. JSON
JSON Schema Example
JSON Schema Example
Given below is a basic JSON schema, which covers a classical product catalog Given below is a basic JSON schema, which covers a classical product catalog description:
description:
{ {
"$schema":
"$schema": "http://json-sche"http://json-schema.org/draft-04/schema.org/draft-04/schema#",ma#", "title": "Product",
"title": "Product",
"description": "A product from Acme's catalog", "description": "A product from Acme's catalog", "type": "object", "type": "object", "properties": { "properties": { "id": { "id": {
"description": "The unique identifier for a product", "description": "The unique identifier for a product", "type": "integer" "type": "integer" }, }, "name": { "name": {
"description": "Name of the product", "description": "Name of the product", "type": "string" "type": "string" }, }, "price": { "price": { "type": "number", "type": "number", "minimum": 0, "minimum": 0, "exclusiveMini
"exclusiveMinimum": mum": truetrue }
} }, },
"required": ["id", "name", "price"] "required": ["id", "name", "price"] }
}
Let's check the various important keywords that can be used in this schema: Let's check the various important keywords that can be used in this schema:
Keywords Description
Keywords Description
$schema
$schema The $schema keyword states that this schema is writtenThe $schema keyword states that this schema is written according to the draft v4 specification.
according to the draft v4 specification.
title
title You You will will use use this this to to give give a a title title to to your your schema.schema.
description
type
type The type keyword defines the first constraint on our JSON data: itThe type keyword defines the first constraint on our JSON data: it has to be a JSON Object.
has to be a JSON Object.
properties
properties Defines various keys and their value types, minimum andDefines various keys and their value types, minimum and maximum values to be used in JSON file.
maximum values to be used in JSON file.
required
required This This keeps keeps a a list list of of required required properties.properties.
minimum
minimum This is the constraint to be put on the value and representsThis is the constraint to be put on the value and represents minimum acceptable value.
minimum acceptable value.
exclusiveMinimum
exclusiveMinimum If "exclusiveMinimum" is present and has boolean value true, theIf "exclusiveMinimum" is present and has boolean value true, the instance is valid if it is strictly greater than the value of instance is valid if it is strictly greater than the value of "minimum".
"minimum".
maximum
maximum This is the constraint to be put on the value and representsThis is the constraint to be put on the value and represents maximum acceptable value.
maximum acceptable value.
exclusiveMaximum
exclusiveMaximum If "exclusiveMaximum" is present and has boolean value true, theIf "exclusiveMaximum" is present and has boolean value true, the instance is valid if it is strictly lower than the value of instance is valid if it is strictly lower than the value of "maximum".
"maximum".
multipleOf
multipleOf A numeric instance is valid against "multipleOf" if the result of theA numeric instance is valid against "multipleOf" if the result of the division of the instance by this keyword's
division of the instance by this keyword's value is an integer.value is an integer.
maxLength
maxLength The length of a string instance is defined as the maximumThe length of a string instance is defined as the maximum number of its characters.
number of its characters.
minLength
minLength The length of a string instance is defined as the minimum numberThe length of a string instance is defined as the minimum number of its characters.
of its characters.
pattern
pattern A string instance is considered valid if the regular expressionA string instance is considered valid if the regular expression matches the instance successfully.
You can check a
You can check a http://json-schema.orghttp://json-schema.org for the complete list of keywords that can befor the complete list of keywords that can be used in defining a JSON schema. The above schema can be used to test the validity of used in defining a JSON schema. The above schema can be used to test the validity of the following JSON code:
the following JSON code:
[ [ { { "id": 2, "id": 2,
"name": "An ice sculpture", "name": "An ice sculpture", "price": 12.50, "price": 12.50, }, }, { { "id": 3, "id": 3,
"name": "A blue mouse", "name": "A blue mouse", "price": 25.50, "price": 25.50, } } ] ]
JSON and XML are human readable formats and are language independent. They both 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 have support for creation, reading and decoding in real world situations. We can compare JSON with XML, based on the following factors:
compare JSON with XML, based on the following factors:
Verbose
Verbose
XML is more verbose than JSON, so it is faster to write JSON for programmers. XML is more verbose than JSON, so it is faster to write JSON for programmers.
Arrays Usage
Arrays Usage
XML is used to describe the structured data, which doesn't include arrays whereas JSON XML is used to describe the structured data, which doesn't include arrays whereas JSON include arrays.
include arrays.
Parsing
Parsing
JavaScript's
JavaScript's eval eval method parses JSON. When applied to JSON, eval returns the describedmethod parses JSON. When applied to JSON, eval returns the described object.
object.
Example
Example
Individual examples of XML and JSON: Individual examples of XML and JSON:
JSON
JSON
{ { "company": Volkswagen, "company": Volkswagen, "name": "Vento", "name": "Vento", "price": 800000 "price": 800000 } }XML
XML
<car> <car> <company>Volkswagen</company> <company>Volkswagen</company> <name>Vento</name> <name>Vento</name> <price>800000</price> <price>800000</price> </car> </car>6. JSON
This chapter covers how to encode and decode JSON objects using PHP programming This chapter covers how to encode and decode JSON objects using PHP programming language. Let's start with preparing the environment to start our programming with PHP language. Let's start with preparing the environment to start our programming with PHP for JSON.
for JSON.
Environment
Environment
As of PHP 5.2.0, the JSON extension is bundled and compiled into PHP by default. As of PHP 5.2.0, the JSON extension is bundled and compiled into PHP by default.
JSON Functions
JSON Functions
Function Libraries
Function Libraries
json_encode
json_encode Returns the JSON representation of a value.Returns the JSON representation of a value.
json_decode
json_decode Decodes a JSON string.Decodes a JSON string.
json_last_error
json_last_error Returns the last error occurred.Returns the last error occurred.
Encoding JSON in PHP (json_encode)
Encoding JSON in PHP (json_encode)
PHP json_encode() function is used for encoding JSON in PHP. This function returns the PHP json_encode() function is used for encoding JSON in PHP. This function returns the JSON representation of a value on success o
JSON representation of a value on success o r FALSE on failure.r FALSE on failure.
Syntax
Syntax
string json_encode ( $value [, $options = 0 ] ) string json_encode ( $value [, $options = 0 ] )
Parameters
Parameters
valuevalue: The value being encoded. This function only works with UTF-8 encoded: The value being encoded. This function only works with UTF-8 encoded
data. data.
optionsoptions: This optional value is a bitmask consisting of JSON_HEX_QUOT,: This optional value is a bitmask consisting of JSON_HEX_QUOT,
JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS,
JSON_NUMERIC_CHECK,JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_NUMERIC_CHECK,JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT.
JSON_FORCE_OBJECT.
7. JSON
Example
Example
The following example shows how to convert an array into JSON with PHP: The following example shows how to convert an array into JSON with PHP:
<?php <?php
$arr = array('a' => 1, 'b' => 2, 'c'
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => => 3, 'd' => 4, 'e' => 5);5); echo
echo json_encode($arr);json_encode($arr); ?>
?>
While executing, this will produce the following result: While executing, this will produce the following result:
{"a":1,"b":2,"c":3,"d":4,"e":5} {"a":1,"b":2,"c":3,"d":4,"e":5}
The following example shows how the PHP objects can be converted into JSON: The following example shows how the PHP objects can be converted into JSON:
<?php <?php class Emp { class Emp { public $name = ""; public $name = ""; public
public $hobbies $hobbies = = "";""; public $birthdate = ""; public $birthdate = ""; } } $e = new Emp(); $e = new Emp(); $e->name = "sachin"; $e->name = "sachin"; $e->hobbies
$e->hobbies = = "sports";"sports";
$e->birthdate = date('m/d/Y h:i:s a', "8/5/1974 12:20:03 p"); $e->birthdate = date('m/d/Y h:i:s a', "8/5/1974 12:20:03 p"); $e->birthdate = date('m/d/Y h:i:s a',
$e->birthdate = date('m/d/Y h:i:s a', strtotime("8/5/197strtotime("8/5/1974 12:20:03"));4 12:20:03"));
echo json_encode($e); echo json_encode($e); ?>
?>
While executing, this will produce the following result: While executing, this will produce the following result:
{"name":"sachin","h
{"name":"sachin","hobbies":"sports","biobbies":"sports","birthdate":"08\/05\/rthdate":"08\/05\/1974 1974 12:20:03 12:20:03 pm"}pm"}
Decoding JSON in PHP (json_decode)
Decoding JSON in PHP (json_decode)
PHP json_decode() function is used for decoding JSON in PHP. This function returns the PHP json_decode() function is used for decoding JSON in PHP. This function returns the value decoded from json to appropriate PHP type.
value decoded from json to appropriate PHP type.
Syntax
Syntax
mixed json_decode ($json [,$assoc = false [, $depth = 512 [, $options = 0 ]]]) mixed json_decode ($json [,$assoc = false [, $depth = 512 [, $options = 0 ]]])
Paramaters
Paramaters
json_string json_string: It is an encoded string which must be UTF-8 encoded data.: It is an encoded string which must be UTF-8 encoded data.
assocassoc: It is a boolean type parameter, when set : It is a boolean type parameter, when set to TRUE, returned objects will beto TRUE, returned objects will be
converted into associative arrays. converted into associative arrays.
depthdepth: It is an integer type parameter which specifies recursion depth: It is an integer type parameter which specifies recursion depth
options: options: It It is is an an integer integer type type bitmask bitmask of of JSON JSON decode,decode,
JSON_BIGINT_AS_STRING is supported. JSON_BIGINT_AS_STRING is supported.
Example
Example
The following example shows how PHP can be used to decode JSON objects: The following example shows how PHP can be used to decode JSON objects:
<?php <?php
$json =
$json = '{"a":1,"b":2,'{"a":1,"b":2,"c":3,"d":4,"e":5}';"c":3,"d":4,"e":5}';
var_dump(json_decode($json)); var_dump(json_decode($json)); var_dump(json_de
var_dump(json_decode($json, code($json, true));true)); ?>
?>
While executing, it will produce the following result: While executing, it will produce the following result:
object(stdClass)#1 (5) { object(stdClass)#1 (5) { ["a"] => int(1) ["a"] => int(1) ["b"] => int(2) ["b"] => int(2) ["c"] => int(3) ["c"] => int(3) ["d"] => int(4) ["d"] => int(4) ["e"] => int(5) ["e"] => int(5) } } array(5) { array(5) { ["a"] => int(1) ["a"] => int(1) ["b"] => int(2) ["b"] => int(2) ["c"] => int(3) ["c"] => int(3) ["d"] => int(4) ["d"] => int(4) ["e"] => int(5) ["e"] => int(5) } }
This
This chapter covers chapter covers how to how to encode and encode and decode JSON decode JSON objects using Pobjects using Perl programmingerl programming language. Let's start with preparing the environment to start our programming with Perl language. Let's start with preparing the environment to start our programming with Perl for JSON.
for JSON.
Environment
Environment
Before you start encoding and decoding JSON using Perl, you need to install JSON Before you start encoding and decoding JSON using Perl, you need to install JSON module, which can be obtained from CPAN. Once you downloaded JSON-2.53.tar.gz or module, which can be obtained from CPAN. Once you downloaded JSON-2.53.tar.gz or any other latest version, follow the steps mentioned b
any other latest version, follow the steps mentioned below:elow:
$tar xvfz
$tar xvfz JSON-2.53.tar.gzJSON-2.53.tar.gz $cd JSON-2.53 $cd JSON-2.53 $perl Makefile.PL $perl Makefile.PL $make $make $make install $make install
JSON Functions
JSON Functions
Function Libraries Function Libraries encode_jsonencode_json Converts the given Perl data structure to a UTF-8 encoded, binaryConverts the given Perl data structure to a UTF-8 encoded, binary string.
string.
decode_json
decode_json Decodes Decodes a a JSON JSON string.string.
to_json
to_json Converts Converts the the given given Perl Perl data data structure structure to to a a json json string.string.
from_json
from_json Expects a json string and tries to parse it, returning the resultingExpects a json string and tries to parse it, returning the resulting reference.
reference.
convert_blessed
convert_blessed Use this function with true value so that Perl can use TO_JSONUse this function with true value so that Perl can use TO_JSON method on the object's class to convert an object into JSON.
method on the object's class to convert an object into JSON.
8. JSON
Encoding JSON in Perl (encode_json)
Encoding JSON in Perl (encode_json)
Perl encode_json() function converts the given Perl data structure to a UTF-8 encoded, Perl encode_json() function converts the given Perl data structure to a UTF-8 encoded, binary string.
binary string.
Syntax:
Syntax:
$json_text = encode_json ($perl_scalar ); $json_text = encode_json ($perl_scalar );
or or
$json_text =
$json_text = JSON->new->utf8->encJSON->new->utf8->encode($perl_scalar);ode($perl_scalar);
Example
Example
The following example shows arrays under JSON with Perl: The following example shows arrays under JSON with Perl:
#!/usr/bin/perl
#!/usr/bin/perl
use JSON; use JSON;
my %rec_hash = ('a' => 1, 'b' =>
my %rec_hash = ('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 2, 'c' => 3, 'd' => 4, 'e' => 5);'e' => 5); my $json =
my $json = encode_json \%rec_hash;encode_json \%rec_hash; print "$json\n";
print "$json\n";
While executing, this will produce the following result: While executing, this will produce the following result:
{"e":5,"c":3,"a":1,"b":2,"d":4} {"e":5,"c":3,"a":1,"b":2,"d":4}
The following example shows how Perl objects can be converted into JSON: The following example shows how Perl objects can be converted into JSON:
#!/usr/bin/perl
#!/usr/bin/perl
package Emp; package Emp; sub new sub new { { my $class = shift; my $class = shift; my $self = { my $self = { name => shift, name => shift, hobbieshobbies => => shift,shift, birthdate
birthdate => => shift,shift, };
};
bless $self, $class; bless $self, $class;
return $self; return $self; }
}
sub TO_JSON { return { %{ shift() } }; sub TO_JSON { return { %{ shift() } }; }}
package main; package main; use JSON; use JSON;
my
my $JSON $JSON = = JSON->new->utf8;JSON->new->utf8; $JSON->convert_blessed(1); $JSON->convert_blessed(1);
$e = new
$e = new Emp( "sachin", "sports", "8/5/1974 12:20:03 pm");Emp( "sachin", "sports", "8/5/1974 12:20:03 pm"); $json =
$json = $JSON->encode($e);$JSON->encode($e); print "$json\n";
print "$json\n";
On executing, it will produce the following result: On executing, it will produce the following result:
{"birthdate":"8/5/1
{"birthdate":"8/5/1974 974 12:20:03 12:20:03 pm","name":"sachin","hopm","name":"sachin","hobbies":"sports"}bbies":"sports"}
Decoding JSON in Perl (decode_json)
Decoding JSON in Perl (decode_json)
Perl decode_json() function is used for decoding JSON in Perl. This function returns the Perl decode_json() function is used for decoding JSON in Perl. This function returns the value decoded from json to an appropriate Perl type.
value decoded from json to an appropriate Perl type.
Syntax:
Syntax:
$perl_scalar = decode_json $json_text $perl_scalar = decode_json $json_text
or or
$perl_scalar =
$perl_scalar = JSON->new->utf8->dJSON->new->utf8->decode($json_text)ecode($json_text)
Example
Example
The following example shows how Perl can be used to decode JSON objects. Here you The following example shows how Perl can be used to decode JSON objects. Here you will need to install Data::Dumper module if you already do not have it on your machine. will need to install Data::Dumper module if you already do not have it on your machine.
#!/usr/bin/perl
#!/usr/bin/perl
use JSON; use JSON; use Data::Dumper; use Data::Dumper; $json$text =
$text = decode_json($json);decode_json($json); print Dumper($text);
print Dumper($text);
On executing, it will produce following result: On executing, it will produce following result:
$VAR1 = { $VAR1 = { 'e' => 5, 'e' => 5, 'c' => 3, 'c' => 3, 'a' => 1, 'a' => 1, 'b' => 2, 'b' => 2, 'd' => 4 'd' => 4 }; };
This chapter covers how to encode and decode JSON objects using Python programming 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 language. Let's start with preparing the environment to start our programming with Python for JSON.
Python for JSON.
Environment
Environment
Before you start with encoding and decoding JSON using Python, you need to install any Before you start with encoding and decoding JSON using Python, you need to install any of the JSON modules available. For this tutorial we have downloaded and installed of the JSON modules available. For this tutorial we have downloaded and installed Demjson (http://deron.meranda.us/python/demjson/)
Demjson (http://deron.meranda.us/python/demjson/) as follows:as follows:
$tar xvfz
$tar xvfz demjson-1.6.tar.gdemjson-1.6.tar.gzz $cd demjson-1.6
$cd demjson-1.6
$python setup.py install $python setup.py install
JSON Functions
JSON Functions
Function Libraries
Function Libraries
encode
encode Encodes Encodes the the Python Python object object into into a a JSON JSON string string representation.representation.
decode
decode Decodes Decodes a a JSON-endoded JSON-endoded string string into into a a Python Python object.object.
Encoding JSON in P
Encoding JSON in Python (encode)
ython (encode)
Python encode() function encodes the Python object into a JSON string representation. Python encode() function encodes the Python object into a JSON string representation.
Syntax
Syntax
demjson.encode(self
demjson.encode(self, , obj, nest_level=0)obj, nest_level=0)
Example
Example
The following example shows arrays under JSON with Python. The following example shows arrays under JSON with Python.
#!/usr/bin/python
#!/usr/bin/python
import demjson import demjson
data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ] data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]
9. JSON
json =
json = demjson.encode(demjson.encode(data)data) print json
print json
While executing, this will produce the following result: While executing, this will produce the following result:
[{"a":1,"b":2,"c":3,"d":4,"e":5}] [{"a":1,"b":2,"c":3,"d":4,"e":5}]
Decoding JSON in Python (decode)
Decoding JSON in Python (decode)
Python can use demjson.decode() function for decoding JSON. This function returns the Python can use demjson.decode() function for decoding JSON. This function returns the value decoded from json to an appropriate Python type.
value decoded from json to an appropriate Python type.
Syntax
Syntax
demjson.decode(self demjson.decode(self, , txt)txt)Example
Example
The following example shows how Python can be used to decode JSON objects. The following example shows how Python can be used to decode JSON objects.
#!/usr/bin/python
#!/usr/bin/python
import demjson import demjson
json
json = = '{"a":1,"b":'{"a":1,"b":2,"c":3,"d":4,"e2,"c":3,"d":4,"e":5}';":5}';
text =
text = demjson.decode(demjson.decode(json)json) print text
print text
On executing, it will produce the following result: On executing, it will produce the following result:
{u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4} {u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4}
This
This chapter covers how chapter covers how to encode to encode and decode JSON and decode JSON objects using Ruby objects using Ruby programmingprogramming language. Let's start with preparing the environment to start our programming with language. Let's start with preparing the environment to start our programming with Ruby for JSON.
Ruby for JSON.
Environment
Environment
Before you start with encoding and decoding JSON using Ruby, you need to install any of Before you start with encoding and decoding JSON using Ruby, you need to install any of the JSON modules available for Ruby. You may need to install Ruby gem, but if you are the JSON modules available for Ruby. You may need to install Ruby gem, but if you are running latest version of Ruby then you must have gem already installed on your running latest version of Ruby then you must have gem already installed on your machine, otherwise let's follow the following single step assuming you already have gem machine, otherwise let's follow the following single step assuming you already have gem installed:
installed:
$gem install json $gem install json
Parsing JSON using Ruby
Parsing JSON using Ruby
The following example shows that the first 2 keys hold string values and the last 3 keys The following example shows that the first 2 keys hold string values and the last 3 keys hold arrays of strings. Let's keep the following content in a file called
hold arrays of strings. Let's keep the following content in a file called input.jsoninput.json..
{ {
"President": "Alan Isaac", "President": "Alan Isaac", "CEO": "David Richardson", "CEO": "David Richardson",
"India": [ "India": [ "Sachin Tendulkar", "Sachin Tendulkar", "Virender Sehwag", "Virender Sehwag", "Gautam Gambhir", "Gautam Gambhir", ], ], "Srilanka": [ "Srilanka": [ "Lasith Malinga", "Lasith Malinga", "Angelo Mathews", "Angelo Mathews", "Kumar Sangakkara" "Kumar Sangakkara" ], ], "England": [ "England": [ "Alastair Cook", "Alastair Cook",
10.
JSON
"Jonathan Trott", "Jonathan Trott", "Kevin Pietersen" "Kevin Pietersen" ] ] } }
Given below is a Ruby program that will be used to parse the above mentioned JSON Given below is a Ruby program that will be used to parse the above mentioned JSON document: document:
#!/usr/bin/ruby
#!/usr/bin/ruby
require 'rubygems' require 'rubygems' require 'json' require 'json' require 'pp' require 'pp' json =json = File.read('inpuFile.read('input.json')t.json') obj =
obj = JSON.parse(json)JSON.parse(json)
pp obj pp obj
On executing, it will produce the following result: On executing, it will produce the following result:
{"President"=>"Alan Isaac", {"President"=>"Alan Isaac", "CEO"=>"David Richardson", "CEO"=>"David Richardson", "India"=> "India"=>
["Sachin Tendulkar", "Virender Sehwag", "Gautam Gambhir"], ["Sachin Tendulkar", "Virender Sehwag", "Gautam Gambhir"],
"Srilanka"=> "Srilanka"=>
["Lasith Malinga ", "Angelo
["Lasith Malinga ", "Angelo Mathews", "Kumar Sangakkara"],Mathews", "Kumar Sangakkara"],
"England"=> "England"=>
["Alastair Cook", "Jonathan Trott", "Kevin Pietersen"] ["Alastair Cook", "Jonathan Trott", "Kevin Pietersen"] }
This
This chapter covers how chapter covers how to encode and to encode and decode JSON objects decode JSON objects using Java programmusing Java programminging language. Let's start with preparing the environment to start our programming with Java language. Let's start with preparing the environment to start our programming with Java for JSON.
for JSON.
Environment
Environment
Before you start with encoding and decoding JSON using Java, you need to install any of Before you start with encoding and decoding JSON using Java, you need to install any of the JSON modules available. For this tutorial we have downloaded and the JSON modules available. For this tutorial we have downloaded and installed
installed JSON.simple (https://code.google.com/p/json-simple/)JSON.simple (https://code.google.com/p/json-simple/) and have added theand have added the location of
location of json-simple-1.1.1.jar json-simple-1.1.1.jar file to the environment variable CLASSPATH.file to the environment variable CLASSPATH.
Mapping between JSON and Java entities
Mapping between JSON and Java entities
JSON.simple maps entities from the left side to the right side while decoding or parsing, JSON.simple maps entities from the left side to the right side while decoding or parsing, and maps entities from the right to the left while encoding.
and maps entities from the right to the left while encoding.
JSON Java JSON Java string java.lang.String string java.lang.String number java.lang.Number number java.lang.Number true|false ava.lang.Boolean true|false ava.lang.Boolean null null null null array java.util.List array java.util.List object java.util.Map object java.util.Map
On decoding, the default concrete class of
On decoding, the default concrete class of java.util.List java.util.List isis org.json.simple.JSONArray org.json.simple.JSONArray andand the default concrete class of
the default concrete class of java.util.Map java.util.Map isis org.json.simple.JSONObject org.json.simple.JSONObject ..
11.
JSON
Encoding JSON in Java
Encoding JSON in Java
Following is a simple example to encode a JSON object using Java JSONObject which is a Following is a simple example to encode a JSON object using Java JSONObject which is a subclass of java.util.HashMap. No ordering is provided. If you need the strict ordering of subclass of java.util.HashMap. No ordering is provided. If you need the strict ordering of elements, use JSONValue.toJSONString (map) method with
elements, use JSONValue.toJSONString (map) method with ordered map implementationordered map implementation such as java.util.LinkedHashMap.
such as java.util.LinkedHashMap.
import
import org.json.simpleorg.json.simple.JSONObject;.JSONObject;
class JsonEncodeDemo class JsonEncodeDemo {
{
public static void main(String[] args) public static void main(String[] args) {
{
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("name", "foo"); obj.put("name", "foo"); obj.put("num", new
obj.put("num", new Integer(100));Integer(100)); obj.put("balanc
obj.put("balance", e", new new Double(1000.21)Double(1000.21));); obj.put("is_vip"
obj.put("is_vip", , new new Boolean(true));Boolean(true));
System.out.print(obj); System.out.print(obj); } } } }
On compiling and executing the above program
On compiling and executing the above program the following result will be generated:the following result will be generated:
{"balance": 1000.21, "num":100,
{"balance": 1000.21, "num":100, "is_vip":true, "name":"foo"}"is_vip":true, "name":"foo"}
Following is another example that shows a JSON object streaming using Java Following is another example that shows a JSON object streaming using Java JSONObject:
JSONObject:
import
import org.json.simpleorg.json.simple.JSONObject;.JSONObject;
class JsonEncodeDemo class JsonEncodeDemo {
{
public static void main(String[] args) public static void main(String[] args) {
{
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("name","foo"); obj.put("name","foo"); obj.put("num",ne
obj.put("balanc
obj.put("balance",new e",new Double(1000.21))Double(1000.21));; obj.put("is_vip
obj.put("is_vip",new ",new Boolean(true));Boolean(true));
StringWriter out =
StringWriter out = new StringWriter();new StringWriter(); obj.writeJSONString(out);
obj.writeJSONString(out);
String jsonText =
String jsonText = out.toString();out.toString(); System.out.print(jsonText); System.out.print(jsonText); } } } }
On compiling and executing the above program
On compiling and executing the above program the following result is generated:the following result is generated:
{"balance": 1000.21, "num":100,
{"balance": 1000.21, "num":100, "is_vip":true, "name":"foo"}"is_vip":true, "name":"foo"}
Decoding JSON in Java
Decoding JSON in Java
The following example makes use of
The following example makes use of JSONObjectJSONObject andand JSONArrayJSONArray where JSONObject iswhere JSONObject is a java.util.Map and JSONArray is a java.util.List, so you can access them with standard a java.util.Map and JSONArray is a java.util.List, so you can access them with standard operations of Map or List.
operations of Map or List.
import
import org.json.simpleorg.json.simple.JSONObject;.JSONObject; import
import org.json.simpleorg.json.simple.JSONArray;.JSONArray; import
import org.json.simpleorg.json.simple.parser.ParseExcept.parser.ParseException;ion; import
import org.json.simpleorg.json.simple.parser.JSONParser;.parser.JSONParser;
class JsonDecodeDemo class JsonDecodeDemo {
{
public static void main(String[] args) public static void main(String[] args) {
{
JSONParser parser=new JSONParser(); JSONParser parser=new JSONParser(); String s
String s = = "[0,{\"1\":{\"2\""[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,:{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";{\"6\":7}]}}}}]"; try{
try{
Object obj =
Object obj = parser.parse(s);parser.parse(s); JSONArray array =
JSONArray array = (JSONArray)obj;(JSONArray)obj; System.out.print
System.out.println("The 2nd element of ln("The 2nd element of array");array"); System.out.println(array.get(1));
System.out.println(array.get(1)); System.out.println();
System.out.println();
JSONObject obj2 =
System.out.print System.out.println("Field ln("Field \"1\"");\"1\""); System.out.println(obj2.get("1")); System.out.println(obj2.get("1")); s = "{}"; s = "{}"; obj =
obj = parser.parse(s);parser.parse(s); System.out.println(obj); System.out.println(obj);
s= "[5,]"; s= "[5,]"; obj =
obj = parser.parse(s);parser.parse(s); System.out.println(obj); System.out.println(obj);
s= "[5,,2]"; s= "[5,,2]"; obj =
obj = parser.parse(s);parser.parse(s); System.out.println(obj); System.out.println(obj); }catch(ParseExc
}catch(ParseException eption pe){pe){ System.out.print
System.out.println("position: " ln("position: " + + pe.getPosition());pe.getPosition()); System.out.println(pe); System.out.println(pe); } } } } } }
On compiling and executing the above program, the following result will be generated: On compiling and executing the above program, the following result will be generated:
The 2nd element of array The 2nd element of array
{"1":{"2":{"3":{"4":[5,{"6":7}]}}}} {"1":{"2":{"3":{"4":[5,{"6":7}]}}}} Field "1" Field "1" {"2":{"3":{"4":[5,{"6":7}]}}} {"2":{"3":{"4":[5,{"6":7}]}}} {} {} [5] [5] [5,2] [5,2]