JSON Tutorial PDF
JSON Tutorial PDF
This tutorial will help you understand JSON and its use within various programming
languages such as PHP, PERL, Python, Ruby, Java, etc.
Audience
This tutorial has been designed to help beginners understand the basic functionality of
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
with JavaScript, Ajax, Perl, etc.
Prerequisites
Before proceeding with this tutorial, you should have a basic understanding of the web
applications work over HTTP and we assume that you have a basic knowledge of
JavaScript.
All the content and graphics published in this e-book are the property of Tutorials Point
(I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or
republish any contents or a part of contents of this e-book in any manner without written
consent of the publisher.
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)
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
website or in this tutorial, please notify us at [email protected]
i
Table of Contents
About the Tutorial .................................................................................................................................... i
Audience .................................................................................................................................................. i
Prerequisites ............................................................................................................................................ i
Number ................................................................................................................................................... 5
String ...................................................................................................................................................... 6
Boolean ................................................................................................................................................... 7
Array ....................................................................................................................................................... 7
Object ..................................................................................................................................................... 8
Whitespace ............................................................................................................................................. 8
null .......................................................................................................................................................... 9
4. JSON OBJECTS................................................................................................................. 10
ii
5. JSON SCHEMA ................................................................................................................ 13
Environment ......................................................................................................................................... 18
JSON Functions...................................................................................................................................... 18
Environment ......................................................................................................................................... 21
JSON Functions...................................................................................................................................... 21
Environment ......................................................................................................................................... 25
JSON Functions...................................................................................................................................... 25
Environment ......................................................................................................................................... 27
iii
11. JSON JSON WITH JAVA .................................................................................................... 29
Environment ......................................................................................................................................... 29
iv
JSON
1. JSON Overview
Uses of JSON
It is used while writing JavaScript based applications that includes browser
extensions and websites.
JSON format is used for serializing and transmitting structured data over network
connection.
Web services and APIs use JSON format to provide public data.
Characteristics of JSON
JSON is easy to read and write.
{
"book": [
{
1
JSON
"id":"01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},
{
"id":"07",
"language": "C++",
"edition": "second"
"author": "E.Balagurusamy"
}]
}
After understanding the above program, we will try another example. Let's save the
below code as json.htm:
<html>
<head>
<title>JSON example</title>
<script language="javascript" >
document.write("<hr />");
document.write(object2.language + " programming language can be studied " +
"from book written by " + object2.author);
document.write("<hr />");
2
JSON
</script>
</head>
<body>
</body>
</html>
Now let's try to open json.htm using IE or any other javascript enabled browser that
produces the following result:
You can refer to JSON Objects chapter for more information on JSON objects.
3
JSON
2. JSON Syntax
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:
Curly braces hold objects and each name is followed by ':'(colon), the
name/value pairs are separated by , (comma).
{
"book": [
{
"id":"01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},
{
"id":"07",
"language": "C++",
"edition": "second"
"author": "E.Balagurusamy"
}]
}
4
JSON
3. JSON DataTypes
Type Description
null empty
Number
It is a double precision floating-point format in JavaScript and it depends on
implementation.
Type Description
5
JSON
Syntax
Example
Example showing Number Datatype, value should not be quoted:
String
It is a sequence of zero or more double quoted Unicode characters with backslash
escaping.
The table shows various special characters that you can use in strings of a JSON
document:
Type Description
\ backslash
/ forward slash
b backspace
f form feed
n new line
r carriage return
t horizontal tab
Syntax
6
JSON
Example
Example showing String Datatype:
Boolean
It includes true or false values.
Syntax
Example
Array
It is an ordered collection of values.
These are enclosed in square brackets which means that array begins with .[. and
ends with .]..
Arrays should be used when the key names are sequential integers.
Syntax
[ value, .......]
Example
Example showing array containing multiple objects:
{
"books": [
{ "language":"Java" , "edition":"second" },
{ "language":"C++" , "lastName":"fifth" },
{ "language":"C" , "lastName":"third" }
]
}
7
JSON
Object
It is an unordered set of name/value pairs.
Objects are enclosed in curly braces that is, it starts with '{' and ends with '}'.
Each name is followed by ':'(colon) and the key/value pairs are separated by ,
(comma).
The keys must be strings and should be different from each other.
Objects should be used when the key names are arbitrary strings.
Syntax
Example
Example showing Object:
{
"id": "011A",
"language": "JAVA",
"price": 500,
}
Whitespace
It can be inserted between any pair of tokens. It can be added to make a code more
readable. Example shows declaration with and without whitespace:
Syntax
Example
8
JSON
null
It means empty type.
Syntax
null
Example
var i = null;
if(i==1)
{
document.write("<h1>value is 1</h1>");
}
else
{
document.write("<h1>value is null</h1>");
}
JSON Value
It includes:
string
boolean
array
object
null
Syntax
Example
var i = 1;
var j = "sachin";
var k = null;
9
JSON
4. JSON Objects
This is an example that shows creation of an object in javascript using JSON, save the
below code as json_object.htm:
<html>
<head>
<title>Creating Object JSON with JavaScript</title>
<script language="javascript" >
</script>
</head>
<body>
</body>
</html>
10
JSON
Now let's try to open json_object.htm using IE or any other javascript enabled browser.
It produces the following result:
<html>
<head>
<title>Creation of array object in javascript using JSON</title>
<script language="javascript" >
var i = 0
document.writeln("<table border='2'><tr>");
for(i=0;i<books.Pascal.length;i++)
{
document.writeln("<td>");
11
JSON
for(i=0;i<books.Scala.length;i++)
{
document.writeln("<td>");
document.writeln("<table border='1' width=100 >");
document.writeln("<tr><td><b>Name</b></td><td width=50>"
+ books.Scala[i].Name+"</td></tr>");
document.writeln("<tr><td><b>Price</b></td><td width=50>"
+ books.Scala[i].price+"</td></tr>");
document.writeln("</table>");
document.writeln("</td>");
}
document.writeln("</tr></table>");
</script>
</head>
<body>
</body>
</html>
Now let's try to open json_array_object.htm using IE or any other javascript enabled
browser. It produces the following result:
12
JSON
5. JSON Schema
JSON Schema is a specification for JSON based format for defining the structure of JSON
data. It was written under IETF draft which expired in 2011. JSON Schema:
Languages Libraries
C WJElement (LGPLv3)
Python Jsonschema
13
JSON
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Product",
"description": "A product from Acme's catalog",
"type": "object",
"properties": {
"id": {
"description": "The unique identifier for a product",
"type": "integer"
},
"name": {
"description": "Name of the product",
"type": "string"
},
"price": {
"type": "number",
"minimum": 0,
"exclusiveMinimum": true
}
},
"required": ["id", "name", "price"]
}
Let's check the various important keywords that can be used in this schema:
Keywords Description
14
JSON
type The type keyword defines the first constraint on our JSON data: it
has to be a JSON Object.
properties Defines various keys and their value types, minimum and
maximum values to be used in JSON file.
15
JSON
You can check a http://json-schema.org for 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
the following JSON code:
[
{
"id": 2,
"name": "An ice sculpture",
"price": 12.50,
},
{
"id": 3,
"name": "A blue mouse",
"price": 25.50,
}
]
16
JSON
6. JSON Comparison with XML
JSON and XML are human readable formats and are language independent. They both
have support for creation, reading and decoding in real world situations. We can
compare JSON with XML, based on the following factors:
Verbose
XML is more verbose than JSON, so it is faster to write JSON for programmers.
Arrays Usage
XML is used to describe the structured data, which doesn't include arrays whereas JSON
include arrays.
Parsing
JavaScript's eval method parses JSON. When applied to JSON, eval returns the described
object.
Example
Individual examples of XML and JSON:
JSON
{
"company": Volkswagen,
"name": "Vento",
"price": 800000
}
XML
<car>
<company>Volkswagen</company>
<name>Vento</name>
<price>800000</price>
</car>
17
JSON
7. JSON JSON with PHP
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
for JSON.
Environment
As of PHP 5.2.0, the JSON extension is bundled and compiled into PHP by default.
JSON Functions
Function Libraries
Syntax
Parameters
value: The value being encoded. This function only works with UTF-8 encoded
data.
18
JSON
Example
The following example shows how to convert an array into JSON with PHP:
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
{"a":1,"b":2,"c":3,"d":4,"e":5}
The following example shows how the PHP objects can be converted into JSON:
<?php
class Emp {
public $name = "";
public $hobbies = "";
public $birthdate = "";
}
$e = new Emp();
$e->name = "sachin";
$e->hobbies = "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', strtotime("8/5/1974 12:20:03"));
echo json_encode($e);
?>
Syntax
19
JSON
Paramaters
json_string: It is an encoded string which must be UTF-8 encoded data.
assoc: It is a boolean type parameter, when set to TRUE, returned objects will be
converted into associative arrays.
Example
The following example shows how PHP can be used to decode JSON objects:
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
20
JSON
8. JSON JSON with Perl
This chapter covers how to encode and decode JSON objects using Perl programming
language. Let's start with preparing the environment to start our programming with Perl
for JSON.
Environment
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
any other latest version, follow the steps mentioned below:
JSON Functions
Function Libraries
encode_json Converts the given Perl data structure to a UTF-8 encoded, binary
string.
from_json Expects a json string and tries to parse it, returning the resulting
reference.
convert_blessed Use this function with true value so that Perl can use TO_JSON
method on the object's class to convert an object into JSON.
21
JSON
Syntax:
or
$json_text = JSON->new->utf8->encode($perl_scalar);
Example
The following example shows arrays under JSON with Perl:
#!/usr/bin/perl
use JSON;
my %rec_hash = ('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
my $json = encode_json \%rec_hash;
print "$json\n";
{"e":5,"c":3,"a":1,"b":2,"d":4}
The following example shows how Perl objects can be converted into JSON:
#!/usr/bin/perl
package Emp;
sub new
{
my $class = shift;
my $self = {
name => shift,
hobbies => shift,
birthdate => shift,
};
bless $self, $class;
22
JSON
return $self;
}
sub TO_JSON { return { %{ shift() } }; }
package main;
use JSON;
my $JSON = JSON->new->utf8;
$JSON->convert_blessed(1);
Syntax:
or
$perl_scalar = JSON->new->utf8->decode($json_text)
Example
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.
#!/usr/bin/perl
use JSON;
use Data::Dumper;
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
23
JSON
$text = decode_json($json);
print Dumper($text);
$VAR1 = {
'e' => 5,
'c' => 3,
'a' => 1,
'b' => 2,
'd' => 4
};
24
JSON
9. JSON JSON with Python
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
Python for JSON.
Environment
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
Demjson (http://deron.meranda.us/python/demjson/) as follows:
JSON Functions
Function Libraries
Syntax
Example
The following example shows arrays under JSON with Python.
#!/usr/bin/python
import demjson
25
JSON
json = demjson.encode(data)
print json
[{"a":1,"b":2,"c":3,"d":4,"e":5}]
Syntax
demjson.decode(self, txt)
Example
The following example shows how Python can be used to decode JSON objects.
#!/usr/bin/python
import demjson
json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
text = demjson.decode(json)
print text
26
JSON
10. JSON JSON with Ruby
This chapter covers how to encode and decode JSON objects using Ruby programming
language. Let's start with preparing the environment to start our programming with
Ruby for JSON.
Environment
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
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
installed:
{
"President": "Alan Isaac",
"CEO": "David Richardson",
"India": [
"Sachin Tendulkar",
"Virender Sehwag",
"Gautam Gambhir",
],
"Srilanka": [
"Lasith Malinga",
"Angelo Mathews",
"Kumar Sangakkara"
],
"England": [
"Alastair Cook",
27
JSON
"Jonathan Trott",
"Kevin Pietersen"
]
}
Given below is a Ruby program that will be used to parse the above mentioned JSON
document:
#!/usr/bin/ruby
require 'rubygems'
require 'json'
require 'pp'
json = File.read('input.json')
obj = JSON.parse(json)
pp obj
{"President"=>"Alan Isaac",
"CEO"=>"David Richardson",
"India"=>
["Sachin Tendulkar", "Virender Sehwag", "Gautam Gambhir"],
"Srilanka"=>
["Lasith Malinga ", "Angelo Mathews", "Kumar Sangakkara"],
"England"=>
["Alastair Cook", "Jonathan Trott", "Kevin Pietersen"]
}
28
JSON
11. JSON JSON with Java
This chapter covers how to encode and decode JSON objects using Java programming
language. Let's start with preparing the environment to start our programming with Java
for JSON.
Environment
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
installed JSON.simple (https://code.google.com/p/json-simple/) and have added the
location of json-simple-1.1.1.jar file to the environment variable CLASSPATH.
JSON Java
string java.lang.String
number java.lang.Number
true|false ava.lang.Boolean
null null
array java.util.List
object java.util.Map
29
JSON
import org.json.simple.JSONObject;
class JsonEncodeDemo
{
public static void main(String[] args)
{
JSONObject obj = new JSONObject();
obj.put("name", "foo");
obj.put("num", new Integer(100));
obj.put("balance", new Double(1000.21));
obj.put("is_vip", new Boolean(true));
System.out.print(obj);
}
}
On compiling and executing the above program the following result will be generated:
Following is another example that shows a JSON object streaming using Java
JSONObject:
import org.json.simple.JSONObject;
class JsonEncodeDemo
{
public static void main(String[] args)
{
JSONObject obj = new JSONObject();
obj.put("name","foo");
obj.put("num",new Integer(100));
30
JSON
obj.put("balance",new Double(1000.21));
obj.put("is_vip",new Boolean(true));
On compiling and executing the above program the following result is generated:
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;
class JsonDecodeDemo
{
public static void main(String[] args)
{
JSONParser parser=new JSONParser();
String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
try{
Object obj = parser.parse(s);
JSONArray array = (JSONArray)obj;
System.out.println("The 2nd element of array");
System.out.println(array.get(1));
System.out.println();
31
JSON
System.out.println("Field \"1\"");
System.out.println(obj2.get("1"));
s = "{}";
obj = parser.parse(s);
System.out.println(obj);
s= "[5,]";
obj = parser.parse(s);
System.out.println(obj);
s= "[5,,2]";
obj = parser.parse(s);
System.out.println(obj);
}catch(ParseException pe){
System.out.println("position: " + pe.getPosition());
System.out.println(pe);
}
}
}
On compiling and executing the above program, the following result will be generated:
Field "1"
{"2":{"3":{"4":[5,{"6":7}]}}}
{}
[5]
[5,2]
32
JSON
12. JSON JSON with Ajax
AJAX is Asynchronous JavaScript and XML, which is used on the client side as a group of
interrelated web development techniques, in order to create asynchronous web
applications. According to the AJAX model, web applications can send and retrieve data
from a server asynchronously without interfering with the display and the behavior of
the existing page.
Many developers use JSON to pass AJAX updates between the client and the server.
Websites updating live sports scores can be considered as an example of AJAX. If these
scores have to be updated on the website, then they must be stored on the server so
that the webpage can retrieve the score when it is required. This is where we can make
use of JSON formatted data.
Any data that is updated using AJAX can be stored using the JSON format on the web
server. AJAX is used so that JavaScript can retrieve these JSON files when necessary,
parse them, and perform one of the following operations:
Store the parsed values in the variables for further processing before displaying
them on the webpage.
It directly assigns the data to the DOM elements in the webpage, so that they are
displayed on the website.
Example
The following code shows JSON with AJAX. Save it as ajax.htm file. Here the loading
function loadJSON() is used asynchronously to upload JSON data.
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<script type="application/javascript">
function loadJSON()
{
var data_file = "http://www.tutorialspoint.com/json/data.json";
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
33
JSON
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 )
{
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
<div class="central">
34
JSON
Given below is the input file data.json, having data in JSON format which will be
uploaded asynchronously when we click the Update Detail button. This file is being kept
in http://www.tutorialspoint.com/json/.
The above HTML code will generate the following screen, where you can check AJAX in
action:
Cricketer Details
Name Country
Sachin India
Update Details:
When you click on the Update Detail button, you should get a result something as
follows. You can try JSON with AJAX yourself, provided your browser supports Javascript.
Cricketer Details
Name Country
Brett Australia
35