Json Quick Guide
Json Quick Guide
Json Quick Guide
JSON or JavaScript Object Notation is a lig htweig ht is a text-based open standard desig ned for humanreadable data interchang e. Conventions used by JSON are known to prog rammers which include C, C++, Java,
Python, Perl etc.
JSON stands for JavaScript Object Notation.
T his format was specified by Doug las Crockford.
T his was desig ned for human-readable data interchang e
JSON has been extended from the JavaScript scripting lang uag e.
JSON filename extension is .json
JSON Internet Media type is applic ation/json
T he Uniform T ype Identifier is public.json
Uses of JSON
JSON is used when writing JavaScript based application which includes browser extension and websites.
JSON format is used for serializing & transmitting structured data over network connection.
JSON is primarily used to transmit data between server and web application.
Web Services and API.s use JSON format to provide public data.
JSON can be used with modern prog ramming lang uag es.
Characteristics of JSON
It is easy to read and write JSON.
JSON is lig htweig ht text based interchang e format
JSON is lang uag e independent.
After understanding the above prog ram we will try another example, let's save the below code as json.htm:
<html>
<head>
<title>JSON example</title>
<script language="javascript" >
var object1 = { "language" : "Java", "author" : "herbert schildt" };
document.write("<h1>JSON with JavaScript example</h1>");
document.write("<br>");
document.write("<h3>Language = " + object1.language+"</h3>");
document.write("<h3>Author = " + object1.author+"</h3>");
var object2 = { "language" : "C++", "author" : "E-Balagurusamy" };
document.write("<br>");
document.write("<h3>Language = " + object2.language+"</h3>");
document.write("<h3>Author = " + object2.author+"</h3>");
document.write("<hr />");
document.write(object2.language + " programming language can be studied " +
"from book written by " + object2.author);
document.write("<hr />");
</script>
</head>
<body>
</body>
</html>
Now let's try to open json.htm using IE or any other javascript enabled browser, this produces the following
result:
JSON - SYNTAX
Let's have a quick look on JSON basic syntax. JSON syntax is basically considered as subset of JavaScript
syntax, it includes the following :
Data is represented in name/value pairs
Curly braces hold objects and each name is followed by ':'(colon), the name/value pairs are separated by ,
(comma).
Square brackets hold arrays and values are separated by ,(comma).
Below is a simple example:
{
"book": [
{
"id":"01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},
{
"id":"07",
"language": "C++",
"edition": "second"
"author": "E.Balagurusamy"
}]
}
JSON - DATATYPES
T here are following datatypes supported by JSON format:
T ype
Desc ription
Number
String
Boolean
true or false
Array
Value
Object
Whitespace
null
empty
Number
It is a double precision floating -point format in JavaScript and it depends on implementation.
Octal and hexadecimal formats are not used.
No NaN or Infinity is used in Number.
T he following table shows number types:
T ype
Desc ription
Integ er
Fraction
Exponent
Syntax:
var json-object-name = { string : number_value, .......}
Example:
Example showing Number Datatype, value should not be quoted:
var obj = {marks: 97}
String
It is a sequence of zero or more double quoted Unicode characters with backslash escaping .
Character is a sing le character string i.e. a string with leng th 1.
T he table shows string types:
T ype
Desc ription
"
double quotation
reverse solidus
solidus
backspace
form feed
new line
carriag e return
horizontal tab
Syntax:
var json-object-name = { string : "string value", .......}
Example:
Example showing String Datatype:
var obj = {name: 'Amit'}
Boolean
It includes true or false values.
Syntax:
var json-object-name = { string : true/false, .......}
Example:
var obj = {name: 'Amit', marks: 97, distinction: true}
Array
It is an ordered collection of values.
T hese are enclosed square brackets which means that array beg ins with .[. and ends with .]..
Arrays should be used when the key names are sequential integ ers.
Syntax:
[ value, .......]
Example:
Example showing array containing multiple objects:
{
"books": [
{ "language":"Java" , "edition":"second" },
{ "language":"C++" , "lastName":"fifth" },
{ "language":"C" , "lastName":"third" }
]
}
Object
It is an unordered set of name/value pairs.
Object are enclosed in curly braces that is it starts with '{' and ends with '}'.
Each name is followed by ':'(colon) and the name/value pairs are separated by , (comma).
Objects should be used when the key names are arbitrary string s
Syntax:
{ string : value, .......}
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 code more readable. Example shows
declaration with and without whitespace:
Syntax:
{string:"
",....}
Example:
var i= "
var j = "
sachin";
saurav"
null
It means empty type.
Syntax:
null
Example:
var i = null;
if(i==1)
{
document.write("<h1>value is 1</h1>");
}
else
{
document.write("<h1>value is null</h1>");
}
JSON Value
It includes:
number (integ er or floating point)
string
boolean
array
object
null
Syntax:
String | Number | Object | Array | TRUE | FALSE | NULL
Example:
var i =1;
var j = "sachin";
var k = null;
JSON - OBJECTS
Creating Simple Objects
JSON objects can be created with Javascript. Let's us see various ways of creating JSON objects using
Javascript:
Creation of an empty Object:
var JSONObj = {};
Creation of an object with attribute bookname with value in string , attribute pric e with numeric value.
Attributes is accessed by using '.' Operator:
var JSONObj = { "bookname ":"VB BLACK BOOK", "price":500 };
T his is an example which shows creation of an object in javascript using JSON, save the below code as
json_objec t.htm:
<html>
<head>
<title>Creating Object JSON with JavaScript</title>
<script language="javascript" >
var JSONObj = { "name" : "tutorialspoint.com", "year" : 2005 };
document.write("<h1>JSON with JavaScript example</h1>");
document.write("<br>");
document.write("<h3>Website Name="+JSONObj.name+"</h3>");
document.write("<h3>Year="+JSONObj.year+"</h3>");
</script>
</head>
<body>
</body>
</html>
Now let's try to open json_object.htm using IE or any other javascript enabled browser, this produces the
following result:
<body>
</body>
</html>
Now let's try to open json_array_object.htm using IE or any other javascript enabled browser, this produces
the following result:
JSON - SCHEMA
JSON Schema is a specification for JSON based format for defining structure of JSON data. It was written under
IET F draft which expired in 2011. JSON Schema:
Describes your existing data format.
Clear, human- and machine-readable documentation.
Complete structural validation, useful for automated testing .
Complete structural validation, validating client-submitted data.
Lang uag es
Libraries
WJElement (LGPLv3)
Java
json-schema-validator (LGPLv3)
.NET
Json.NET (MIT )
ActionScript 3
Frig g a (MIT )
Haskell
aeson-schema (MIT )
Python
Jsonschema
Ruby
PHP
JavaScript
Orderly (BSD); JSV; json-schema; Matic (MIT ); Dojo; Persevere (modified BSD or
AFL 2.0); schema.js.
{
"$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 various important keywords which can be used in this schema:
Keywords
Desc ription
$schema
T he $schema keyword states that this schema is written according to the draft v4
specification.
title
description
type
T he 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.
required
minimum
T his is the constraint to be put on the value and represents minimum acceptable value.
exclusiveMinimum
If "exclusiveMinimum" is present and has boolean value true, the instance is valid if it is
strictly g reater than the value of "minimum".
maximum
T his is the constraint to be put on the value and represents maximum acceptable value.
exclusiveMaximum
If "exclusiveMaximum" is present and has boolean value true, the instance is valid if it is
strictly lower than the value of "maximum".
multipleOf
A numeric instance is valid ag ainst "multipleOf" if the result of the division of the instance
by this keyword's value is an integ er.
maxLeng th
minLeng th
pattern
A string instance is considered valid if the reg ular expression matches the instance
successfully.
You can check a http://json-schema.org for complete list of keywords which can be used in defining JSON
schema. Above schema can be used to test the validity of the below g iven JSON code:
[
{
"id": 2,
"name": "An ice sculpture",
"price": 12.50,
},
{
"id": 3,
"name": "A blue mouse",
"price": 25.50,
}
]
Verbose
XML is more verbose than JSON, so it's faster to write JSON for humans.
Arrays Usag e
XML is used to describe 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
T his shows 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>
Environment
As of PHP 5.2.0, the JSON extension is bundled and compiled into PHP by default.
JSON Functions
Func tion
Libraries
json_encode
json_decode
json_last_error
Syntax:
string json_encode ( $value [, $options = 0 ] )
Parameters:
value: T he value being encoded. T his function only works with UT F-8 encoded data.
options: T his optional value is a bitmask consisting of JSON_HEX_QUOT , JSON_HEX_T AG,
JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK,JSON_PRET T Y_PRINT ,
JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT
Example
T he following example shows how to convert an arrays into JSON with PHP:
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
T he following example shows how 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', strtotime("8/5/1974 12:20:03"));
echo json_encode($e);
?>
Syntax:
mixed json_decode ($json [,$assoc = false [, $depth = 512 [, $options = 0 ]]])
Paramaters:
json_string : It is encoded string which must be UT F-8 encoded data
assoc : It is a boolean type parameter, when set to T RUE, returned objects will be converted into
associative arrays.
depth: It is an integ er type parameter which specifies recursion depth
options: It is an integ er type bitmask of JSON decode, JSON_BIGINT _AS_ST RING is supported.
Example
T he 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));
?>
int(1)
int(2)
int(3)
int(4)
int(5)
Environment
Before you start with encoding and decoding JSON using Perl, you will need to install JSON module which can be
obtained from CPAN. Once you downloaded JSON-2.53.tar.g z or any other latest version, follow the following
steps:
$tar xvfz JSON-2.53.tar.gz
$cd JSON-2.53
$perl Makefile.PL
$make
$make install
JSON Functions
Func tion
Libraries
encode_json
Converts the g iven Perl data structure to a UT F-8 encoded, binary string .
decode_json
to_json
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 T O_JSON method on the object's
class to convert an object into JSON.
Syntax:
$json_text = encode_json ($perl_scalar );
or
$json_text = JSON->new->utf8->encode($perl_scalar);
Example
T he 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";
T he 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;
return $self;
}
sub TO_JSON { return { %{ shift() } }; }
package main;
use JSON;
my $JSON = JSON->new->utf8;
$JSON->convert_blessed(1);
Syntax:
$perl_scalar = decode_json $json_text
or
$perl_scalar = JSON->new->utf8->decode($json_text)
Example
T he 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}';
$text = decode_json($json);
print Dumper($text);
=>
=>
=>
=>
=>
5,
3,
1,
2,
4
Environment
Before you start with encoding and decoding JSON using Python, you will need to install any of the JSON
modules available. For this tutorial I downloaded and installed Demjson as follows:
$tar xvfz demjson-1.6.tar.gz
$cd demjson-1.6
$python setup.py install
JSON Functions
Func tion
Libraries
encode
decode
Syntax:
demjson.encode(self, obj, nest_level=0)
Example
T he following example shows arrays under JSON with Python
#!/usr/bin/python
import demjson
data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]
json = demjson.encode(data)
print json
Syntax:
demjson.decode(self, txt)
Example
T he 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
Environment
Before you start with encoding and decoding JSON using Ruby, you will need to install any of the JSON modules
available for Ruby. You may need to install Ruby g em, but if yo are running latest version of Ruby then you must
have g em already installed on your machine, otherwise let's follow the following sing le step assuming you already
have g em installed:
$gem install json
T he following is ruby prog ram which will be used to parse above mentioned JSON document:
#!/usr/bin/ruby
require 'rubygems'
require 'json'
require 'pp'
json = File.read('input.json')
obj = JSON.parse(json)
pp obj
Environment
Before you start with encoding and decoding JSON using Java, you will need to install any of the JSON modules
available. For this tutorial I downloaded and installed JSON.simple and add the location of json-simple1.1.1.jar file to environment variable CLASSPAT H:
J SO N
J ava
string
java.lang .String
number
java.lang .Number
true|false
ava.lang .Boolean
null
null
array
java.util.List
object
java.util.Map
While decoding , default concrete class of java.util.List is org.json.simple.JSONArray and default concrete
class of java.util.Map is org.json.simple.JSONObject.
While compile and executing above prog ram, this will produce following result:
{"balance": 1000.21, "num":100, "is_vip":true, "name":"foo"}
Following is another example which shows JSON object streaming using Java JSONObject:
import org.json.simple.JSONObject;
class JsonEncodeDemo
{
public static void main(String[] args)
{
While compile and executing above prog ram, this will produce following result:
{"balance": 1000.21, "num":100, "is_vip":true, "name":"foo"}
org.json.simple.JSONObject;
org.json.simple.JSONArray;
org.json.simple.parser.ParseException;
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();
JSONObject obj2 = (JSONObject)array.get(1);
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);
}
}
}
While compile and executing above prog ram, this will produce following result:
The 2nd element of array
{"1":{"2":{"3":{"4":[5,{"6":7}]}}}}
Field "1"
{"2":{"3":{"4":[5,{"6":7}]}}}
{}
[5]
[5,2]
Example
T he below code shows JSON with Ajax, save it in ajax.htm file. Here loading function loadJSON() will be 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");
}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);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
document.getElementById("Name").innerHTML = jsonObj.name;
document.getElementById("Country").innerHTML = jsonObj.country;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
</script>
<title>tutorialspoint.com JSON</title>
</head>
<body>
<h1>Cricketer Details</h1>
<table >
<tr><th>Name</th><th>Country</th></tr>
<tr><td><div >Sachin</div></td>
<td><div >India</div></td></tr>
</table>
<div >
<button type="button" onclick="loadJSON()">Update Details </button>
</body>
</html>
Following is the input file data.json having data in JSON format which will be uploaded asynchronously when we
click Update Detail button. T his file is being kept in http://www.tutorialspoint.com/json/
{"name": "brett", "country": "Australia"}
Above HT ML code will g enerate following screen, where you can check AJAX in action:
CRICKETER DETAILS
Name
Country
CRICKETER DETAILS
Name
Country