You are on page 1of 74

JSON Tutorial - Introduction

This is an introductory tutorial on JSON - JavaScript Object Notation. As a web developer, you will
find plenty of occasion when you will require applying or working with JSON in your project. This
tutorial begins a set of tutorials on JSON and discusses definition, specification, What JSON looks
like in real world, a bit of History of JSON, comparison between Relational Database and JSON, a
brief understanding of when to elect JSON over Relational Database, XML vs JSON, Syntax of
JSON, typical examples of real world uses of JSON.
The document ends with a list of what you will learn in other tutorials of this series, which is sort of a
roadmap of basic things you need to learn for working with JSON and a summary of the points
discussed.
Ultimately, JSON is used as a data model, but compared to other data models like Relational
Database or XML, it has a low learning curve. In fact, if you are familiar with any of the modern day
programming language (e.g PHP, JavaScript, Ruby) you are already familiar with the data structures
used in JSON. Moreover, any modern programming language can work with JSON. May be that is
why JSON has got wide acceptance from the developer community. The following visual
representation from Google Trend may help you to understand the how JSON is gaining popularity
over years.
According to EWeek, The famous Tech news and views magazine, JSON is considered as one of
the most demanded skills in the year 2013.

What is JSON
JSON is a lightweight text-based open standard data-interchange format. It is human readable.
JSON is derived from a subset of JavaScript programming language (Standard ECMA-262 3rd
EditionDecember 1999). It is entirely language independent and can be used with most of the
modern programming languages.
JSON is often used to serialize and transfer data over a network connection, for example between
web server and a web application. In computer science, serialization is a process to transforming
data structures and objects in a format suitable to be stored in a file or memory buffer or transmitted
over a network connection. Later on, this data can be retrieved. Because of the very nature of the
JSON, it is useful for storing or representing semi structured data
JSON is a standard and is specified on RFC4627 on IETF (International Engineering Task Force).
The specification is made by Doglus Crockford on July 2006.
JSON files are saved with .json extension. Internet media type of JSON is "application/json".

What JSON looks like

We will now look how a typical JSON looks like. The following code snippet is a valid (you will see in
a later chapter what is syntactically valid JSON) JSON representing information about a book.
view plainprint?

1. {
2.

"Title": "The Cuckoo's Calling",

3.

"Author": "Robert Galbraith",

4.

"Genre": "classic crime novel",

5.

"Detail": {

6.

"Publisher": "Little Brown",

7.

"Publication_Year": 2013,

8.

"ISBN-13": 9781408704004,

9.

"Language": "English",

10.

"Pages": 494

11.

},

12.

"Price": [

13.

14.

"type": "Hardcover",

15.

"price": 16.65

16.

},

17.

18.

"type": "Kidle Edition",

19.

"price": 7.03

20.
21.

}
]

22. }
Now we will discuss what are basic constructs of JSON.

Basic Constructs

There four basic and built-in data types in JSON. They are strings, numbers, booleans (i.e true and
false) and null. Besides there are two data types which are structured - objects and arrays.

Objects are wrapped within '{' and '}'. Arrays are enclosed by '[' and ']'. Objects are list of label-value
pairs. Arrays are list of values.

Both objects and arrays can be nested.

strings, numbers, booleans (i.e true and false) and null can be used as values.

Following image and then text following will be useful to get you started with how JSON data is
constructed.

So the entire content of the JSON data shown above is enclosed within an object. "Title": "The
Cuckoo's Calling", "Author": "Robert Galbraith", "Genre": "classic crime novel", these are label-value
pairs separated by commas. Labels and their values are separated by a colon (:). Notice that both
labels and values are enclosed by quotations, since they are strings.
Notice the '"Detail"' label then. It contains another object, which again contains several label-value
pairs. This is an example of how nesting (object within object in this case) is done in JSON.

Then '"Price"' label contains an array, which is turn contains two separate objects. Another example
of nesting.
Also notice that numbers are not enclosed by quotations.

History of JSON
The name behind popularizing the JSON is Douglas Crockford. He used JSON is his company State
Software around 2001.
In 2005, Yahoo started using JSON in it's web services.
In later 2006, Google started offering JSON in it's Gdata web protocol.
Today, JSON is one of the most widely used data-interchange format in web, and supported by most
of the Web APIs (like twitter api) to fetch public data and creating applications out of them.

Comparison with Relational Database


Since JSON is used to host/represent data, we will discuss how it is different from the traditional
Relational Database model used in RDBMS systems like MySQL, SQL Server etc. This may be
useful for you to choose JSON over RDBMS or RDBMS over JSON depending upon the type and
structure of data you want to deal with. Let's start with a comparison against certain features:

Structure : In relational database, it is tables, which are responsible for storing data in form of rows
and columns. JSON uses objects and arrays - objects are label-value pairs and arrays are list of values.
They can be nested recursively.
Metadata : In relational database, it is schema, which is used for storing data about the structure and
type of the data to be stored and schemas are pre defined, i.e. they are created at the time of creation of
database and tables, before you can store data. JSON also may use schema, to have a definition of the
structure and type of data to represented, but it is not pre defined. Most of the time it is self describing,
even if it uses a schema, it comes with much more flexibility than a schema used in relational database.
But it would be judgmental to say that it is an advantage of JSON over Relational Database. Having an pre
defined schema may have several benefits depending upon the data to be dealt with.
Retrieving data : Relational databases use Structured Query Language, a expressive and very
powerful language, based on relational algebra to fetch data from database. JSON does not have any
widely used or accepted language to query the data stored. JAQL and JSONiq are many of the query
languages which mostly are work in progress to query data from JSON.
Sorting : SQL does the job in case of Relational Database. In case of JSON, since arrays often used,
in programs, arrays can be sorted.
Application : There are many open source as well as commercial Relational Database systems are
available - like MySQL, POstgreSQL, SQL Server, Oracle, DB2 etc. JSON is mostly applied with
programming languages. But, there is also NoSQL systems. NoSQL systems use JSON format to store
data. Some of the NoSQL systems use JSON format are - MongoDB, CoucheDB etc.
Learning curve: JSON is a clear winner here. Since the basic data types and structure used here are
similar to those used in many programming languages, it is obvious that if you are coming from a
programming background, you will pick things up in JSON pretty fast. RDBMS is a separate field of

study on the other hand. But definitely, time you invest to learn Relational database return you several
opportunities and benefits.
Now let's discuss a few use cases which will be useful.
Assume that you have to store information regarding students(name, id, class) and marks obtained
by them in various subjects. Relational Database is suitable here than using JSON, since here we
can have one table containing student detail and another table for marks obtained by them in various
subjects.
Now assume that we have to represent information regarding students(name, id, class) and various
projects they have completed in different subjects along with a brief description of the project.
Assume that a student may complete any number of projects and any of number subjects they
choose from. Notice that, in this case you may have any uniformity of the data to be stored. So, in
this case JSON will be preferable than using Relational Database.

JSON vs XML
Since XML is also used as data interchange format widely, we will try to draw a comparison between
them. The purpose of the comparison it's definitely not in the line of which is better, rather we will try
to understand which one is suitable for storing specific kind of data.

XML is more expressive than JSON. XML sometimes also suffers from using tags repeatedly, where
as JSON is much more concise.
XML is more complex than JSON.

There are several specifications to define schema(metadata) for XML, for example DTD and XSD.
JSON schema is there for doing the same for JSON, but it is not as widely used as XML schemas.

XML can be used with most of the programming languages as JSON. But the point is, when you are
working with XML, then you have you are actually trying match two systems those data structures are
different. In case of JSON though, since objects and arrays are basic data structures used, it is easy to work
with them in programs.

For selecting specific parts of an XML document, there is standard specification called XPath. This is
widely used. In JSON, we have JSONPath to do the same, but not widely in use.

XML has Xquery specification for querying XML data. JSON though have JAQL, JSONiq etc, but
they are not in use widely.

XML has XSLT specification which may be used to apply style to an XML document. JSON does not
have any such thing.

Typical uses of JSON


API : API is the most widely used area where JSON is used for data exchange. Specially, web
applications those have a social face, it has become obvious now that they have an API, so that

developers can consume the huge amount of data collected by the app and then can create
derivative apps. Twitter, Facebook, Linkedin, Flicker, Dribble, you name it, all the well known apps on
internet today has an API and uses JSON as their preferred format for serving data to the
developers. Out of these APIs, some have support for both JSON and XML, but some support only
JSON.
We will see a simple demonstration of rottentomatoes API to get a feel of how JSON is used in APIs.
In this demo, we are querying the rottentomatoes.com for name and thumbnail poster of the movie
containing string "Life is beautiful" using JavaScript and Jquery. It returns the result in JSON format
and then it is displayed on browser. You can have a live demo by clicking here. And following is a
screenshot of it.

NoSQL : This is another area where JSON is used. NoSQL databases like MongoDb, CouchDb
uses JSON format to store data.
Since JSON structures can be transformed to JavaScript objects within the browser environment, it is
very easy to work with. Moreover it can be integrated with server side JavaScript also. The following
shows that in mongoDb, data is stored in JSON format (to be specific, a variant of JSON, called
BSON is used). You can learn MongoDb in detail in our separate tutorial for MongoDb.
we select the database first. Our database name is w3r_demo here.

Now we will insert some data to the collection (like table in RDBMS) books. The data we are entering
is shown at the JSON data example above in this example.

We will select the data insert and display now.

So this way we store data in JSON format in NoSQL database MongoDb.


AJAX : JSON is often used to retrieve data from server with AJAX. This is suitable because this way,
retrieved data is presented to browser environment and then using JavaScript can be manipulated
and rendered.
In the following demo we are using Jquery and AJAX to fetch the most recent 5 photographs of cats
from Flicker. We can view a live demo here. And following is a screenshot.

Package Management : Since the complexity of web development has increased a lot, developers
nowadays use tools to create a package of their application. That makes the app more easily deployable and later on it is also become easy to make modifications and integrate the changes. This way,
the development and maintenance process becomes easier. There are number of package

management tools are available, namely Bower, Yomen , NPM (Node Package Manager) etc. Most
of these tools use a package.json file where the metadata (like name, version, description, file
structure, dependencies, license information etc) are written.
Bellow is the package.json file from Twitter Bootstrap.
view plainprint?

1. {
2.
3.

"name": "bootstrap"
, "description": "Sleek, intuitive, and powerful front-end framework for faster an
d easier web development."

4.

, "version": "2.3.2"

5.

, "keywords": ["bootstrap", "css"]

6.

, "homepage": "http://twitter.github.com/bootstrap/"

7.

, "author": "Twitter Inc."

8.

, "scripts": { "test": "make test" }

9.

, "repository": {

10.
11.

"type": "git"
, "url": "https://github.com/twitter/bootstrap.git"

12. }
13. , "licenses": [
14.

15.

"type": "Apache-2.0"

16.
17.

, "url": "http://www.apache.org/licenses/LICENSE-2.0"
}

18. ]
19. , "devDependencies": {
20.

"uglify-js": "1.3.4"

21.

, "jshint": "0.9.1"

22.

, "recess": "1.1.8"

23.

, "connect": "2.1.3"

24.

, "hogan.js": "2.0.0"

25. }
26. }
So, you already might have an idea of how JSON is being used in real world and will be useful for
you to learn JSON well, so that you can use it in your own projects.

What you will learn in JSON tutorials of w3resource


Here is a brief rundown of the tutorials you will come across in our series of JSON tutorials.

A detail discussion about data structures and values you can use in JSON.
Various tools you may use to view JSON online.
How to use JSONLint to validate JSON.
Some examples with explanations of JSON.
Working with PHP and JSON. We have discussed installation, how to various PHP functions to
explore the power of JSON.
Working with JavaScript and JSON. JSON is a built in object in JavaScript. We have discussed how to
convert JSON to string and string to JSON.
To select specific parts of a JSON data, you can use JSON Path. We have discussed how to use
JavaScript and PHP to work with JSON Path.
If you are sending a query to fetch data residing on a domain different than domain from where the
request is sent, you have to use JSONP to overcome a cross domain resource sharing bottleneck. We have
discussed JSONP in a separate tutorial in this series.
We have also discussed BSON, a variant of JSON, used in MongoDb to store data.

Conclusion
It will be good idea to have a quick recap of what we have learnt in this introductory tutorial of JSON.
here we go

JSON is a open,text based, light-weight data interchange format specified as RFC4627, came to the
developer world in 2005 and it's popularity is increased rapidly.

JSON uses Object and Array as data structures and strings, number, true, false and null as values.
Objects and arrays can be nested recursively.

Most (if not all) modern programming languages can be used to work with JSON.

NoSQL databases, which are evolved to get rid of the bottlenecks of the Relational Databases, are
using JSON to store data.
JSON gives developers a power to choose between XML and JSON leading to more flexibility.
Besides NoSQL, AJAX, Package Management, and integration of APIs to the web application are the
major areas where JSON is being used extensively.

Hopefully, this tutorial sets the ground well to start learning JSON through our consequent tutorials.
By the way, we are in the process of going through the a major update of our present JSON tutorials,
more useful content is going to be added to serve a better and improved learning material to our
users. Subscribe to our RSS Feed to stay updated.
photo credit: superfluity via photopin cc
- See more at: http://www.w3resource.com/JSON/introduction.php#sthash.CqaW9ksI.dpuf

Description
In this page you will learn about structures of JSON. you will also learn different forms of storing data
in JSON.

Data Structures supported by JSON


JSON supports two widely used (amongst programming languages) data structures.
A collection of name/value pairs. Different programming languages support this data structure in
different names. Like object, record, struct, dictionary, hash table, keyed list, or associative array.
An ordered list of values. In various programming languages, it is called as array, vector, list, or
sequence.
Since data structure supported by JSON is also supported by most of the modern programming
languages, it makes JSON a very useful data-interchange format.

Data Types in JSON


JSON supports an array of data types. We will discuss those in detail in the following section of this
page of the JSON tutorial.

Object
Syntax
{ string : value, .......}

Explanation of Syntax
An object starts and ends with '{' and '}'. Between them, a number of string value pairs can reside.
String and value is separated by a ':' and if there are more than one string value pairs, they are
separated by ','.

Example
{
"firstName": "Bidhan",
"lastName": "Chatterjee",
"age": 40,
"email":"bidhan@example.com"
}
In JSON, objects can nest arrays (starts and ends with '[' and ']') within it. The following example
shows that.

{
"Students": [
{ "Name":"Amit Goenka" ,
"Major":"Physics" },
{ "Name":"Smita Pallod" ,
"Major":"Chemistry" },
{ "Name":"Rajeev Sen" ,
"Major":"Mathematics" }
]
}

Array
Syntax
[ value, .......]

Explanation of Syntax
An Array starts and ends with '[' and ']'. Between them, a number of values can reside. If there are
more than one values reside, they are separated by ','.

Example
[100, 200, 300, 400]
If the JSON data describes an array, and each element of that array is an object.
[
{
"name": "Bidhan Chatterjee",
"email": "bidhan@example.com"
},
{
"name": "Rameshwar Ghosh",
"email": "datasoftonline@example.com"
}
]
Remember that even arrays can also be nested within an object. The following shows that.

{
"firstName": "Bidhan",
"lastName": "Chatterjee",
"age": 40,
"address":
{
"streetAddress": "144 J B Hazra Road",
"city": "Burdwan",
"state": "Paschimbanga",
"postalCode": "713102"
},
"phoneNumber":
[
{
"type": "personal",
"number": "09832209761"
},
{
"type": "fax",
"number": "91-342-2567692"
}
]
}

Value

Syntax
String || Number || Object || Array || TRUE || FALSE || NULL
A value can be a string, a number, an object, an Array, a Boolean value (i.e. true or false) or Null.
This structure can be nested.

String
A string is a sequence of zero or more Unicode characters, enclosed by double quotes, using
backslash escapes. A character is represented as a single character string, similar to a C or Java
string.
The following table shows supported string types.

String Types

Description

"

A double quotation mark.

Reverse Solidus

Solidus

Backspace

form feed

newline

Carriage return

Horizontal tab

Four hexadecimal digits

Number
The following table shows supported number types.

Number Types

Description

Integer

Positive or negative Digits.1-9. And 0.

Fraction

Fractions like .8.

Exponent

e, e+, e-, E, E+, E-

Whitespace
Whitespace can be placed between any pair of supported data-types.
photo credit: monteregina via photopin cc
- See more at: http://www.w3resource.com/JSON/structures.php#sthash.VV3K4Us0.dpuf

Objective
While working with JSON, often you may need a JSON viewer. This document discusses several
online JSON viewer. Hopefully, this will help you to select one depending upon your requirement.

jsonviewer.stack.hu
This may be the most widely used online JSON viewer. Indeed it is feature rich to be used widely.

You can directly copy your JSON text in this online viewer. Or you may use the load JOSN data
button to supply an url and the viewer will load JSON form that resource. After the JSON code is
visible in the viewer, you can click on Format to format the code.

Clicking on Viewer then will change the mode of the viewer and you can expand or collapse the
JSON tree on the left hand side pane to view the name and values on the right hand side pane.

In the Text mode, you can minify the JSON code by clicking on the Remove white space.

And finally, you can clear the code by clicking on Clear.

jsoneditoronline.org

jsoneditoronline.org is another excellent JOSN viewer. It comes with a default JSON code which you
may clear by clicking on clear button.You may load your own JSON code by clicking on Open and
then you choose to open from a local file (Open file) and form a url (Open url).

You click on JSON to editor and you can see the code you loaded as a JSON tree on the right hand
side pane.

You can then expand and collapse the tree to view various components of the JSON tree.

There is search box on the editor, which you may use to search various components of the JSON
code.

Once you click on the Save button, the document in question is saved on your local machine (within
default download location).
On the left hand pane, the left most button is to format your JSON code.

And the button net to that is to remove all the white spaces and make it compact.

Online JSON Tree Viewer Tool


This is tool is located at http://www.jquery4u.com/demos/online-json-tree-viewer/. You can either
click on Choose a file and upload a JSOn file or you may click on Copy and Paste and simply copy
JSON code from a source.

Once the code is there, click on the Generate JSON tree to obtain a tree view of the JSON code.

You can now Collapse and Expand the JSON tree. Another good feature of this tool is, when you
select a component of the JSON tree, you can see a popup on the browser showing you the path of
the JSON object selected.

You can not save, clear or remove white space using this tool though.

JSON Visualization
This is feature rich online JSON viewer, available at http://chris.photobooks.com/json/default.htm.
You can paste the JSON code under Input. You may also click Load and load a JSON file from
remote.

Click on render to generate either JSON or HTML, depending upon the selection you have made
under radio boxes of Output.

By clicking on Expand/Collapse you can expand and collapse the JSON tree rendered. You can click
on any of the JSON component and it shows it's location in the JSON tree.

Clicking on validate will validate your JSON code.


Clicking on reencode will reencode the JSON code.

Json viewer
This tool is available at http://www.jsonviewer.com/. Like other tools, this also allows you to load
JSON from either url or you can directly paste the code. Though the loading from url is available on
IE only. After you click on Parse JSON data, Json Object view is rendered.

JSON Parser Online

You can access this tool at http://json.parser.online.fr/. Once you paste code on the left hand side
panel, you can view JSON tree w.r.t string parsing and eval.

Clicking on the Options opens a menu and you can choose various options from there.

This tool has several JSON samples including one Invalid JSON sample which is great, particularly
for beginners.

Free Online JSON Parser


http://jsonparser.com/ offers this tool. You can copy code, format, view JSON tree and collapse and
expand the tree with this tool.

JSONView in Chrome
This browser extension for Chrome is an excellent tool. You can obtain it from
https://chrome.google.com/webstore/detail/jsonview/chklaanhfefbnpoihckbnefhakgolnmc?hl=en. You
can use the context menu to copy the JSON path or the value.

This has an extension for Firefox also. You can obtain it from here:https://addons.mozilla.org/ENus/firefox/addon/jsonview/.
You have any other tool in mind? Let us know. And of course share it with your friends and
colleagues.
photo credit: superfluity via photopin cc
- See more at: http://www.w3resource.com/JSON/online-JSON-viewer.php#sthash.4JsUwbSO.dpuf

Description
In this page you will see how you can validate your JSON data using JSONLint.

What is JSONLint
JSONLint is an opensource project which allows you to validate your JSON data. Since when you
are working with any programming language and JSON, if your JSON data is not properly formatted,
it can cause error, it is better to validate your JSON data beforehand.
You can check your JSON data by simply copying it to the JSONLint online (http://jsonlint.com/).

Example of validating JSON with JSONLint


We will take simple piece of code and with the help of JSONLint, we will validate that. Here is the
code
{ "firstName": "Bidhan", "lastName": "Chatterjee", age: 40, "email":bidhan@example.com }

Upon copying this code in the JSONLint and pressing Validate button, it shows the following error :

So you can see that it shows you the line number and the kind of error occurred.
Here, it says that it says that 'age' must be written as a string on line number 3. So, we enclose age
as "age" directly in the JSONLint and press validate button again.
Here is the output :

Now it says that the error is on line 5. It should be "bidhan@example.com" instead of


bidhan@example.com. And after making that change it validates the JSON.
..

- See more at: http://www.w3resource.com/JSON/validate-JSON-withJSONLint.php#sthash.G7ofwi8S.dpuf

Description
This document provides you with some JSON Example. Examples are associated with XML,
MySQL, MongoDB and APIs to add more value. Instead of just writing the JSON code as examples,
we thought that it would be of more value to you if we co-relate the examples with those.
If you want to read about various formats JSON can be stored with, you may refer JSON Data
Structure.
The following is an example of a JSON document. Bellow that. the XML format of the same
document is given.
All of the JSON documents used in this document are validated with JSONLint.

XML and JSON


JSON Document

{
"Dogs": [
{
"category": "Companion dogs",
"name": "Chihuahua"
},
{
"category": "Hounds",
"name": "Foxhound"
}
]
}
XML Document

<dogs>
<dog>
<category>companion dogs</category>
<breed>Chihuahua</breed>
</dog>
<dog>
<category>Hounds</category>
<breed>Foxhound</breed>
</dog>
</dogs>

MySQL and JSON


The following is a MySQL table. Using the PHP-MySQL code bellow the table, we have created a
JSON document.
MySQL Table

PHP MySQL code to extract data from MySQL table and display as JSON.

<?php
$host="localhost"; //replace with your hostname
$username="root"; //replace with your username
$password=""; //replace with your password
$db_name="demo"; //replace with your database
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select * from emp_info"; //replace emp_info with your table name
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_row($result)){
$json['emp_info'][]=$row;
}
}
mysql_close($db_name);
echo json_encode($json);
// please refer to our PHP JSON encode function tutorial for learning json_encode function in
detail
?>
JSON Document
{"emp_info":[["Rameshwar Ghosh","rameshwar@example.com"],["Bidhan
Chatterjee","bidhan@example.com"],["Rebati Banerjee","rebati@example.com"]]}

MongoDB and JSON


The following example shows how MongoDB stores data in JSON format. We have a table called
'userdetails' and if we run a query to select all the records of
the table, we get data in JSON format.

Tumblr API and JSON


tumblr.com is messaging platform. It offers an API to retrieve data. Here is a simple command to
retrieve blog information. For the sake of simplicity, we have kept authentication method out of the
scope of this document.
http://api.tumblr.com/v2/blog/web-development-and-seo.tumblr.com/info
Where "web-development-and-seo" is the blog name from where you want to retrieve data. When
browser is pointed to this URL, we get following output, which is in JSON format.
{"meta":{"status":401,"msg":"Not Authorized"},"response":[]}.
photo credit: superfluity via photopin cc
- See more at: http://www.w3resource.com/JSON/JSON-example.php#sthash.GWCCQpXG.dpuf

Description
In this page you will learn about installing JSON in PHP and about PHP json_decode() function with
real world examples.

Installation

PHP 5.2.0 supports JSON out of the box. So, when you install PHP, JSON support is automatically
installed and you don't need any installation and configuration in addition.
If your PHP version is less that 5.2.0, you can run the following command on RHEL5/CentOS5 Linux.
sudo yum install php-pecl-json

JSON Functions
JSON supports three PHP functions : json_decode, json_encode and json_last_error. We will
discuss all of these functions with examples in the following section of this page.

json_decode() Function
Description
json_decode() function decodes a JSON string. Suppose you have obtained some data in JSON
format and you want to convert it into PHP variable for the purpose of presenting that data to user or
use it for further programming, you have to use this function.

PHP Version
PHP 5 >= 5.2.0, PECL json >= 1.2.0

Syntax
json_decode(json_string, assoc, depth, options)

Parameters
Parameters

Type

Description

json_string

String

A JSON encoded string. It must be a UTF-8 encoded data.

assoc

Boolean

If it is true, returned object will be converted into an associative arr

depth

Integer

Specifies recursion depth. This is user specified.

Options

Integer

Bitmask of JSON decode. As of this writing, only JSON_BIGINT_

Return Values

json_decode() function returns an supported PHP type. If the available JSON string can not be
decoded or if the encoded data is deeper than the recursion limit, it returns NULL. Values true and
false are returned as TRUE, FALSE.

Example - fetching last ten tweets from a twitter user's


timeline
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PHP JSON installation and json_decode() function | JSON tutorial | w3resource</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
function GetJsonFeed($url)
{
$feed = file_get_contents($url);
return json_decode($feed);
}
$tweets = GetJsonFeed("http://twitter.com/status/user_timeline/w3resource.json?count=10");
// w3resource is the twitter username in question
?>
<h1>Last ten tweets in w3resource's timeline</h1>
<p>
<?php
//Loop through the feed list and display the text part. text is an element in the json feed returned
by the twitter API
foreach ($tweets as $tweet)
{
?>
<p>
<?php
echo $tweet -> text;
?>
</p>
<?php
}
?>
</body>
</html>
Note : As far as you are connected to the internet, you can run the above code from localhost also.
Replace w3resource with the user name of your choice.

Output of the above Example


.
.

photo credit: Jeni Rodger via photopin cc

<<PreviousNext>>

- See more at: http://www.w3resource.com/JSON/php-json-installation-and-decodefunction.php#sthash.bpaHWlov.dpuf

Description
In this page you will learn about PHP json_encode() function with example.

json_encode() Function
Description

PHP json_encode() function coverts a PHP value into a JSON value. For example, from a PHP
array, it can create a JSON representation of that array.

PHP Version
PHP 5 >= 5.2.0, PECL json >= 1.2.0

Syntax
json_encode(value, options)

Parameters
Parameters

Type

Description

value

Mixed

Any PHP type except resource. Must be UTF character encoded data.

options

Integer

Bitmask comprising of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JS


JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT.

Return Values
json_encode() function returns a string, if the function works.

Example of PHP json_encode example


<?php $w3r_one = array('php',"'MySQL'",'"SQL"','<?PHP ?>');
echo "Normal: ", json_encode($w3r_one), "\n";
echo "Tags: ", json_encode($w3r_one, JSON_HEX_TAG), "\n";
echo "Apos: ", json_encode($w3r_one, JSON_HEX_APOS), "\n";
echo "Quot: ", json_encode($w3r_one, JSON_HEX_QUOT), "\n";
echo "Amp: ", json_encode($w3r_one, JSON_HEX_AMP), "\n";
echo "All: ", json_encode($w3r_one, JSON_HEX_TAG | JSON_HEX_APOS |
JSON_HEX_QUOT | JSON_HEX_AMP), "\n\n";
$w3r_two = array();
echo "Empty array output as array: ", json_encode($w3r_two), "\n";
echo "Empty array output as object: ", json_encode($w3r_two, JSON_FORCE_OBJECT),
"\n\n";
$w3r_three = array(array(1,2,3));
echo "output of the above Non-associative array as array: ", json_encode($w3r_three), "\n";
echo "output of the above Non-associative array as object: ", json_encode($w3r_three,
JSON_FORCE_OBJECT), "\n\n";

$w3r_four = array('PHP' => 'examples', 'MySQL' => 'With PHP');


echo "output of the associative array as always an object: ", json_encode($w3r_four), "\n";
echo "output of the associative array as always an object: ", json_encode($w3r_four,
JSON_FORCE_OBJECT), "\n\n";
?>

Output of the example of PHP json_encode function

photo credit: nickj365 via photopin cc

<<PreviousNext>>

- See more at: http://www.w3resource.com/JSON/php-json-encode-function.php#sthash.iWdBKX3J.dpuf

Introduction
In this page you will learn about PHP json_last_error() function with examples.

Description
While working on encoding or decoding JSON, if an error occur, json_last_error() function returns the
last error.

PHP version
PHP 5 >= 5.3.0

Syntax
json_last_error ()

Parameters
json_last_error() function does not have any parameters.

Return values
json_last_error() function returns an integer.
The following table shows the values which are CONSTANTS :

Constants

Description

JSON_ERROR_NONE

Specifies that no error occurred.

JSON_ERROR_DEPTH

Specifies that the maximum stack depth has been exceeded.

JSON_ERROR_STATE_MISMATCH

Indicates that the associated JSON is not properly formed or invalid.

JSON_ERROR_CTRL_CHAR

Indicates that the error is in control characters. This usually happens i

JSON_ERROR_SYNTAX

Indicates that this is a syntax error.

JSON_ERROR_UTF8

Indicates that error occurred due to malformed UTF-8 characters, wh


incorrect encoding.

json_last_error() example
<?php $w3r_json[] = "{'Website': 'w3resource.com'}";
//since we have used "'" instead of double quote (""), it is a syntax error.
foreach ($w3r_json as $w3r_string) {
json_decode($w3r_string);
switch (json_last_error()) {
case JSON_ERROR_NONE:
echo ' - No errors';
break;
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';

break;
default:
echo ' - Unknown error';
break;
}
echo PHP_EOL;
}
?>

Output of the above example

photo credit: irvken via photopin cc


- See more at: http://www.w3resource.com/JSON/php-json_last_error-function.php#sthash.xBpyIqsg.dpuf

Discription
In this page you will learn about working with JSON and JavaScript. We have discussed
JSON.stringify, JSON.parse with examples.
We have also discussed why you should not use JavaScript eval() while working with JSON.

What is serialize and deserialize


Often you would find these two terms - serialize and deserialize. With the context of working with
JavaScript and JSON, in a nutshell, to get JSON value from JavaScript value is serialization and
when it's other way (JSON to JavaScript) is deserialization.

JavaScript JSON object


The JavaScript JSON object comprises methods using which you can convert JavaScript values to
JSON format and JSON notation to JavaScript values.
We will now discuss two JSON methods - JSON.stringify and JSON.parse with examples.

JSON.stringify
JSON.stringify is used to convert JavaScript values to JSON.

JSON.stringify example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html
xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JavaScript JSON.stringify example | JSON tutorial | w3resource</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body onload="w3resource();">
<h1>This is an example of JavaScript JSON.stringify</h1>
<script type="text/javascript">
function w3resource()
{
var w3r = {};
w3r.PHP = "w3resource PHP tutorial";
w3r.Examples = 500;
var w3r_JSON = JSON.stringify(w3r); // w3r_JSON holds {"PHP":"w3resource PHP
tutorial","Examples":500}
alert (w3r_JSON);
}
</script>
</body>
</html>
View the Example of JavaScript JSON.stringify online.

JSON.parse
JSON.parse is used to convert JSON notation to JavaScript values.

JSON.parse example
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JavaScript JSON.parse example | JSON tutorial | w3resource</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body onload="w3resource();">
<h1>This is an example of JavaScript JSON.stringify</h1>
<script type="text/javascript">
function w3resource()
{
var w3r = {};

w3r.PHP = "w3resource PHP tutorial";


w3r.Examples = 500;
var w3r_JSON = JSON.stringify(w3r); // w3r_JSON holds {"PHP":"w3resource PHP
tutorial","Examples":500}
alert(w3r_JSON);
var convertToJS = JSON.parse(w3r_JSON);
var StringAgain = JSON.stringify(w3r);
alert(StringAgain);
}
</script>
</body>
</html>
View the Example of JavaScript JSON.parse online.

Why you should not use eval() with JSON


It's not safe to parse JSON using eval because eval allows much more syntax than JSON. Even it
can be extended up execution of arbitrary code, which leaves a big security whole for your website.
photo credit: nyuhuhuu via photopin cc
- See more at: http://www.w3resource.com/JSON/working-with-javascript.php#sthash.Pw78nRmN.dpuf

Description
In this page you will learn how to work with JSONPath and JavaScript.

What is JSONPath
JSONPath is a lightweight library to find and extract sections from a JSON data. It can be used with
both JavaScript and PHP.

Obtain JSONPath
To work with JSONPath and JavaScript, you need to download jsonpath.js. You can download it from
http://code.google.com/p/jsonpath/.
Once downloaded, you need to include the said js file in your webpage and you are ready to use it.

Syntax

jsonPath(obj, expr [, args])

Parameters
Parameter

Description

obj (object|array)

This parameter represents the Object representing the JSON struc

expr (string)

This parameter represents JSONPath expression string.

args (object|undefined)

This parameter represents Object controlling path evaluation and

args.resultType ("VALUE"|"PATH")

By default, this parameter causes the result to be matching values

Return Values
Return value

Description

array

An array comprising either values or normalized path expressions which match the path

false

This is returned if no match is found.

Example of using JSONPath with JavaScript


The JSON we will be working with is as follows :

{ "MovieDatabase": {
"movie": [
{ "name":"The Change-Up",
"genre": "comedy",
"director": "David Dobkin",
"Facebook_like": 252
},
{ "name":"Rise of the Planet of the Apes",
"genre": "SciFi",
"director": "Rupert Wyatt",
"Facebook_like": 472
},
{ "name":"30 Minutes or Less",
"genre": "adventure",
"director": "Ruben Fleischer",
"Facebook_like": 114
},
{ "name":"Final Destination 5",

"genre": "Horror",
"director": "Steven Quale",
"Facebook_like": 241
}
]
}
}
JavaScript Code to find and extract various parts of the above JSON data is as follows (note that
since we will be using a method from json.js parser, you need to download and include that too ) :

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JavaScript JSONPath example | JSON tutorial | w3resource</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="/JSON/json.js"></script>
<script type="text/javascript" src="/JSON/jsonpath.js"></script>
</head>
<body>
<h1>This is an example of JavaScript with JSONPath</h1>
<script type="text/javascript">
var json = { "MovieDatabase": {
"movie": [
{ "name":"The Change-Up",
"genre": "comedy",
"director": "David Dobkin",
"Facebook_like": 252
},
{ "name":"Rise of the Planet of the Apes",
"genre": "SciFi",
"director": "Rupert Wyatt",
"Facebook_like": 472
},
{ "name":"30 Minutes or Less",
"genre": "adventure",
"director": "Ruben Fleischer",
"Facebook_like": 114
},
{ "name":"Final Destination 5",
"genre": "Horror",
"director": "Steven Quale",
"Facebook_like": 241
}
]
}
};
result = "";
result += jsonPath(json, "$.MovieDatabase.movie[*].director").toJSONString() + "<br />";

//find all directors result += jsonPath(json, "$..director").toJSONString() + "<br />";


//find all directors result += jsonPath(json, "$.MovieDatabase.*").toJSONString() + "<br />";
//find all movies result += jsonPath(json, "$.MovieDatabase..Facebook_like").toJSONString() +
"<br />";
//find all facebook lies of all the movies result += jsonPath(json, "$..movie[(@.length1)]").toJSONString() + "<br />";
//the last movie in data result += jsonPath(json, "$..movie[-1:]").toJSONString() + "<br />";
//the last movie in data result += jsonPath(json, "$..movie[0,1]").toJSONString() + "<br />";
//first two movies result += jsonPath(json, "$..movie[:3]").toJSONString() + "<br />";
//first three movies result += jsonPath(json, "$..movie[?(@.genre)]").toJSONString() + "<br />";
//all movies with genre result += jsonPath(json, "$..movie[?
(@.Facebook_like>200)]").toJSONString() + "<br />";
//movies with facebook like more that 200 result += jsonPath(json, "$..*").toJSONString() +
"\n";
// all members in the JSON document document.write(result);
</script>
</body>
</html>
View the example of working with JSONPath and JavaScript online.
Practice the example of working with JSONPath and JavaScript online.
photo credit: brentbat via photopin cc

<<PreviousNext>>

- See more at: http://www.w3resource.com/JSON/JSONPath-withJavaScript.php#sthash.QKgOkBF6.dpuf

Description
In this tutorial we will discuss using JSONPath with PHP to find and extract parts of the JSON data
If you are unfamiliar with JSONPath, please also read w3resource's JSONPath with JavaScript
tutorial.

Obtain JSONPath
To work with JSONPath and PHP, you need to download jsonpath.php. You can download it from
http://code.google.com/p/jsonpath/.
Once downloaded, you need to include the said PHP file in your webpage and you are ready to use
it.

Syntax

jsonPath(obj, expr [, args])

Parameters
Parameter

Description

obj (object|array)

This parameter represents the Object representing the JSON stru

expr (string)

This parameter represents JSONPath expression string.

args (object|undefined)

This parameter represents Object controlling path evaluation and

args['resultType'] ("VALUE"|"PATH")

By default, this parameter causes the result to be matching value

Return Values
Return value

Description

array

An array comprising either values or normalized path expressions which match the path

false

This is returned if no match is found.

Example of using JSONPath with PHP


The JSON we will be working with is as follows :

{ "MovieDatabase": {
"movie": [
{ "name":"The Change-Up",
"genre": "comedy",
"director": "David Dobkin",
"Facebook_like": 252
},
{ "name":"Rise of the Planet of the Apes",
"genre": "SciFi",
"director": "Rupert Wyatt",
"Facebook_like": 472
},
{ "name":"30 Minutes or Less",
"genre": "adventure",
"director": "Ruben Fleischer",
"Facebook_like": 114
},
{ "name":"Final Destination 5",

"genre": "Horror",
"director": "Steven Quale",
"Facebook_like": 241
}
]
}
}
PHP Code to find and extract various parts of the above JSON data is as follows (note that since we
will be using a JSON parser of Michal Migurski, you need to download and include that too ) :

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PHP JSONPath example | JSON tutorial | w3resource</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
&</head>
<body>
<h1>This is an example of PHP with JSONPath</h1>
<?php
require_once('json.php');
require_once('jsonpath-0.8.1.php');
$json = '{ "MovieDatabase": {
"movie": [
{ "name":"The Change-Up",
"genre": "comedy",
"director": "David Dobkin",
"Facebook_like": 252
},
{ "name":"Rise of the Planet of the Apes",
"genre": "SciFi",
"director": "Rupert Wyatt",
"Facebook_like": 472
},
{ "name":"30 Minutes or Less",
"genre": "adventure",
"director": "Ruben Fleischer",
"Facebook_like": 114
},
{ "name":"Final Destination 5",
"genre": "Horror",
"director": "Steven Quale",
"Facebook_like": 241
}
]
}
}';
$parser = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
$json_object = $parser->decode($json);

$result = "";
$result .= $parser->encode(jsonPath($json_object, "$.MovieDatabase.movie[*].director")) .
"<strong> : find all directors</strong>
"; $result .= $parser->encode(jsonPath($json_object, "$..director")) . "<strong> : find all
directors</strong>
"; $result .= $parser->encode(jsonPath($json_object, "$.MovieDatabase.*")) . "<strong> : find
all movies</strong>
"; $result .= $parser->encode(jsonPath($json_object, "$.MovieDatabase..Facebook_like")) .
"<strong> : find all facebook lies of all the movies</strong>
"; $result .= $parser->encode(jsonPath($json_object, "$..movie[(count(@)-1)]")) . "<strong> :
the last movie in data</strong>
"; $result .= $parser->encode(jsonPath($json_object, "$..movie[-1:]")) . "<strong> : the last
movie in data</strong>
"; $result .= $parser->encode(jsonPath($json_object, "$..movie[0,1]")) . "<strong> : the first two
movies in data</strong>
"; $result .= $parser->encode(jsonPath($json_object, "$..movie[:4]")) . "<strong> : the fourth
movie in data</strong>
"; $result .= $parser->encode(jsonPath($json_object, "$..movie[?(@['genre'])]")) . "<strong> :
genres of all the movies in data</strong>
"; $result .= $parser->encode(jsonPath($json_object, "$..movie[?(@['Facebook_like']>200)]")) .
"<strong> : movies with facebook like more than 200</strong>
"; $result .= $parser->encode(jsonPath($json_object, "$..*")) . "<strong> : All the info in
data</strong>
"; print($result); ?>
View the example of working with JSONPath and PHP online.
Practice the example of working with JSONPath and PHP online.
photo credit: VinothChandar via photopin cc

<<Previous

- See more at: http://www.w3resource.com/JSON/JSONPath-with-PHP.php#sthash.3aZzr6p9.dpuf

Description
In this page we have discussed BSON - Binary JSON.

What is BSON
A single entity in BSON is called as document. A document comprised of zero or more key/value
pairs(like associative arrays) in binary format.

Datatypes
BSON supports the following basic datatypes :

byte : 1 byte, i.e. 8 bits.


int32 : 4 bytes i.e. 32-bit signed integer.
int64 : 8 bytes i.e. 64-bit signed integer.
double : 8 bytes i.e. 64-bit IEEE 754 floating point

The following table describes the rest specifications of a BSON document :

Grammar

Description

document ::= int32 e_list "\x00"

BSON Document : init32 ref

e_list ::= element e_list | ""

Sequence of elements.

element ::= "\x01" e_name double

Floating point.

element ::= "\x02" e_name string

UTF-8 string.

element ::= "\x03" e_name document

Embedded document.

element ::= "\x04" e_name document

Array.For example ['x','y'] wi

element ::= "\x05" e_name binary

Binary data

element ::= "\x06" e_name

Undefined(this has been depr

element ::= "\x07" e_name (byte*12)

ObjectId

element ::= "\x08" e_name "\x00"

Boolean "false"

element ::= "\x08" e_name "\x01"

Boolean "true"

element ::= "\x09" e_name int64

UTC milliseconds in UNIX e

element ::= "\x0A" e_name

Null value

element ::= "\x0B" e_name cstring cstring

Regular expression

element ::= "\x0C" e_name string (byte*12)

DB Pointer. This has been de

element ::= "\x0D" e_name string

JavaScript Code.

element ::= "\x0E" e_name string

Symbol.

element ::= "\x0F" e_name code_w_s

JavaScript code w/ scope.

element ::= "\x10" e_name int32

32-bit Integer.

element ::= "\x11" e_name int64

Timestamp.

element ::= "\x12" e_name int64

64-bit integer.

element ::= "\xFF" e_name

Min key.

element ::= "\x7F" e_name

Max key.

e_name ::= cstring

Key name.

string ::= int32 (byte*) "\x00"

String.

cstring ::= (byte*) "\x00"

CString.

binary ::= int32 subtype (byte*)

Binary.

subtype ::= "\x00"

Binary / Generic.

subtype ::= "\x01"

Function.

subtype ::= "\x02"

Old generic subtype.

subtype ::= "\x03"

UUID.

subtype ::= "\x05"

MD5.

subtype ::= "\x80"

User defined.

code_w_s ::= int32 string document

Code w/ scope.

Implementation
There are several BSON libraries available in various languages like - ActionScript,C,C# / .Net, C++
or stand-alone C++, Delphi, Erlang, Factor, Fantom, Go, Haskell, Java, J2ME (work in progress),

Lisp, Perl, PHP, Python with optional C extension, Python 3, Ruby with optional C extension,
Standard ML (SML)
MongoDB, which is a NoSQL database, stores data in BSON format.

Comparison between BSON and JSON


For the sake of faster navigation within BSON, it adds some extra fields that JSON, like length
prefixes. Because of this, though it is designed to be taken less space that JSON, in practice,
sometimes JSON takes less space.
BSON is faster than JSON when it comes to encoding and decoding.
photo credit: Rakka via photopin cc
- See more at: http://www.w3resource.com/JSON/BSON.php#sthash.llwHFNl0.dpuf

Introduction to JSONP
In this page We will discuss JSONP, i.e. JSON with padding. JSONP is used to request data from a
server residing in a different domain. But why do we need a special technique to access data from a
different domain? It's because of the Same Origin Policy.

Same Origin Policy


In general, this policy states that, if protocol (like http), Port number (like 80) and host (like
example.com) is different from where data is being requested, it should not be permitted.
But HTML <script> element is allowed to perform content retrieval from foreign origins.

How JSONP works - Step by Step


Step 1 - You need to create a callback function. The function accepts some data. Like following code
:

function w3r_callback(data){
console.log(data);
}
Step 2 - Include a script in your web page which contains the callback function created a step 1 as a
parameter.

<script src="http://www.example.com?q=w3r_callback"><script>

Step 3 - It outputs a script which calls the function and requested data is passed.

w3r_callback({
"FirstName" : "xyz",
"LastName" : "abc",
"Grade" : "A"
}
);

Note
JSONP has nothing to do with Ajax, since it does not use XMLHttpRequest. Instead it dynamically
inserts <script> tag in to a webapge.
But if you are using Jquery to do this sort of a job, you got to use Jquery's Ajax utility. Something like
following -

$.ajax({
// ...
dataType: 'jsonp',
// ...
});

Where to use JSONP


JSONP is mostly used to get data using RESTFull APIs(like Flicker).

Example - getting the latest updates from the flicker


regarding tag "dogs" using Jquery and JSONP
<!DOCTYPE html>
<html>
<head>
<style>img{ height: 100px; float: left; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>An JSONP example from w3resource</title>
</head>
<body>
<div id="images">
</div>
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
tags: "dogs",

tagmode: "any",
format: "json"
},
function(data) {
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
if ( i == 3 ) return false;
});
});</script>
</body>
</html>
View the output of above JSONP example in a separate browser window.

<<Previous

- See more at: http://www.w3resource.com/JSON/JSONP.php#sthash.hNXQLbsB.dpuf

What is JSON Schema


In this tutorial we will discuss JSON Schema, a proposed Internet draft defining a JSON media type
(application/schema+json). Internet Engineering Task Force defines JSON Schema as follows:
"JSON (JavaScript Object Notation) Schema defines the media type "application/schema+json", a
JSON based format for defining the structure of JSON data. JSON Schema provides a contract for
what JSON data is required for a given application and how to interact with it. JSON Schema is
intended to define validation, documentation, hyperlink navigation, and interaction control of JSON
data."

Goals of JSON Schema


There are three main goals of JSON Schema: Validation, Documentation and Hyperlinking. We will
discuss these three goals in brief in a moment.

Validation
Suppose there is an application which may interact with many different JSON services. So, there is a
requirement for validation, i.e. you need to validate your JSON objects.

Documentation
This allows you to fetch documentation information form JSON Schema. Which in turn, may be used
to match your data and also can be used for user interaction.

Hyperlinking
Heyperlinks can be created into the parts of your JSON data by coupling them with the JSON
Schema.

JSON Schema validation Libraries


Following table gives an overview of JSON Schema libraries available :

Languages

Libraries

WJElement (LGPLv3).

Java

json-schema-validator (LGPLv3).

.NET

Json.NET (MIT).

ActionScript 3

Frigga (MIT).

Haskell

aeson-schema (MIT).

Python

jsonschema.

Ruby

autoparse (ASL 2.0); ruby-jsonschema (MIT).

PHP

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

JavaScript

Orderly (BSD); JSV; json-schema; Matic (MIT); Dojo; Persevere (modified BSD

Available Schemas
Core Meta-Schema
This is the meta-schema definition for type/validation part of Schemas themselves. The Schema is
as following:
view plainprint?

1. {
2.

"id" : "http://json-schema.org/schema#",

3.

"type" : ["object","string"],

4.

"format": "uri",

5.
6.

"properties" : {

7.

"type" : {

8.

"type" : ["string", "array"],

9.

"items" : {

10.

"type" : ["string", "#"]

11.

},

12.

"uniqueItems" : true,

13.

"default" : "any"

14.

},

15.
16.

"properties" : {

17.

"type" : "object",

18.

"additionalProperties" : "#",

19.

"default" : {}

20.

},

21.
22.

"items" : {

23.

"type" : ["#", "array"],

24.

"items" : "#",

25.

"default" : {}

26.
27.

},

28.

"required" : {

29.

"type" : "boolean",

30.

"default" : false

31.

},

32.
33.

"additionalProperties" : {

34.

"type" : ["#", "boolean"],

35.

"default" : {}

36.

},

37.

"additionalItems" : {

38.

"type" : ["#", "boolean"],

39.

"default" : {}

40.

},

41.
42.

"requires" : {

43.
44.

"type" : ["string", "#"]


},

45.
46.

"minimum" : {

47.
48.

"type" : "number"
},

49.
50.
51.

"maximum" : {
"type" : "number"

52.

},

53.
54.

"exclusiveMinimum" : {

55.

"type" : "number"

56.

},

57.
58.

"exclusiveMaximum" : {

59.

"type" : "number"

60.

},

61.
62.

"minItems" : {

63.

"type" : "integer",

64.

"minimum" : 0,

65.

"default" : 0

66.

},

67.
68.

"maxItems" : {

69.
70.

"type" : "integer"
},

71.
72.

"uniqueItems" : {

73.

"type" : "boolean",

74.

"default" : false

75.

},

76.
77.

"pattern" : {

78.

"type" : "string",

79.

"format" : "regex"

80.

},

81.
82.

"minLength" : {

83.

"type" : "integer",

84.

"minimum" : 0,

85.

"default" : 0

86.

},

87.
88.

"maxLength" : {

89.
90.

"type" : "integer"
},

91.
92.

"enum" : {

93.

"type" : "array",

94.

"minItems" : 1,

95.

"uniqueItems" : true

96.

},

97.
98.
99.

"title" : {
"type" : "string"

100.

},

101.
102.

"description" : {

103.
104.

"type" : "string"
},

105.
106.

"format" : {

107.
108.

"type" : "string"
},

109.
110.

"maxDecimal" : {

111.

"type" : "number",

112.

"minimum" : 0

113.

},

114.
115.

"disallow" : {

116.

"type" : ["string", "array", "#"],

117.

"items" : {

118.

"type" : ["string", "#"]

119.

},

120.

"uniqueItems" : true

121.

},

122.
123.

"extends" : {

124.

"type" : ["#", "array"],

125.

"items" : "#",

126.

"default" : {}

127.

128.

},

129.

"links" : [

130.

131.

"href" : "{id}",

132.

"rel" : "self"

133.

134.

],

135.
136.

"default" : {}

137.

138.

Hyper Meta-Schema
This is for schemas with link definition. The Schema is as following:
view plainprint?

1. {
2.

"id": "http://json-schema.org/hyper-schema",

3.
4.

"properties": {

5.

"links": {

6.

"type": "array",

7.

"items": { "$ref": "http://json-schema.org/links" }

8.

},

9.
10.

"fragmentResolution": {

11.

"type": "string",

12.

"default": "slash-delimited"

13.

},

14.
15.

"root": {

16.

"type": "boolean",

17.

"default": false

18.

},

19.
20.

"readonly": {

21.

"type": "boolean",

22.

"default": false

23.

},

24.
25.

"pathStart": {

26.

"type": "string",

27.

"format": "uri"

28.
29.

},

30.

"mediaType": {

31.
32.

"type": "string"
},

33.
34.

"alternate": {

35.

"type": "array",

36.

"items": { "$ref": "http://json-schema.org/hyper-schema-or-uri" }

37.

},

38.
39.

"type": {

40.

"type": [ "string", "array" ],

41.

"items": {

42.

"type": [ "string", { "$ref": "http://json-schema.org/hyper-schema-oruri" } ]

43.

},

44.

"uniqueItems": true,

45.

"default": "any"

46.

},

47.
48.

"properties": {

49.

"type": "object",

50.

"additionalProperties": { "$ref": "http://json-schema.org/hyper-schema-oruri" },

51.
52.

"default": {}
},

53.
54.

"items": {

55.

"type": [ { "$ref": "http://json-schema.org/hyper-schema-or-uri" }, "array"


],

56.

"items": { "$ref": "http://json-schema.org/hyper-schema-or-uri" },

57.

"default": {}

58.

},

59.

"additionalProperties": {

60.

"type": [ { "$ref": "http://json-schema.org/hyper-schema-or-uri" }, "boolea


n" ],

61.

"default": {}

62.

},

63.

"additionalItems": {

64.

"type": [ { "$ref": "http://json-schema.org/hyper-schema-or-uri" }, "boolea


n" ],

65.

"default": {}

66.

},

67.

"contentEncoding": {

68.

"type": "string"

69.

},

70.
71.

"default": {

72.

},

73.
74.

"requires": {

75.

"type": [ "string", { "$ref": "http://json-schema.org/hyper-schema-or-uri" }


]

76.

},

77.

"disallow": {

78.

"type": [ "string", "array", { "$ref": "http://json-schema.org/hyper-schemaor-uri" } ],

79.

"items": {

80.

"type": [ "string", { "$ref": "http://json-schema.org/hyper-schema-oruri" } ]

81.

},

82.

"uniqueItems": true

83.

},

84.

"extends": {

85.

"type": [ { "$ref": "http://json-schema.org/hyper-schema-or-uri" }, "array


"],

86.

"items": { "$ref": "http://json-schema.org/hyper-schema-or-uri" },

87.

"default": {}

88.

89.
90.

},

91.
92.
93.

"links": [
{

94.

"href": "{$schema}",

95.

"rel": "describedby"

96.

},

97.
98.

99.

"href": "{$ref}",

100.

"rel": "full"

101.

102.

],

103.
104.

"fragmentResolution": "dot-delimited",

105.

"extends": { "$ref": "http://json-schema.org/schema" }

106.

107.

JSON Referencing
This Schema defines a generic linking mechanism used by meta-schemas for liking. The Schema is
as following:
view plainprint?

1. {
2.

"$schema": "http://json-schema.org/hyper-schema",

3.

"id": "http://json-schema.org/json-ref",

4.
5.

"items": { "$ref": "#" },

6.

"additionalProperties": { "$ref": "#" },

7.
8.
9.

"links": [
{

10.

"href": "{$ref}",

11.

"rel": "full"

12.

},

13.
14.

15.

"href": "{$schema}",

16.

"rel": "describedby"

17.

},

18.
19.

20.

"href": "{id}",

21.

"rel": "self"

22.
23.

}
]

24.
25.

"fragmentResolution": "json-pointer"

26. }
27.

JSON Schema Interfaces


This schema is for meta-schema definition for schemas which define class-style method interfaces
for programming languages. The Schema is as following:
view plainprint?

1. {
2.

"extends":"http://json-schema.org/hyper-schema",

3.

"description":"A schema for schema interface definitions that describe progra


mmatic class structures using JSON schema syntax",

4.

"properties":{

5.

"methods":{

6.

"type":"object",

7.

"description":"This defines the set of methods available to the class insta


nces",

8.

"additionalProperties":{

9.

"type":"object",

10.

"description":"The definition of the method",

11.

"properties":{

12.

"parameters":{

13.
14.

"type":"array",
"description":"The set of parameters that should be passed to the
method when it is called",

15.

"items":"#",

16.

"required": true

17.

},

18.

"returns":"#"

19.

20.

21.
22.
23. }
24.

}
}

Geographic Coordinate Card


This Schema is for microformat style representation of a person, company, organization or place.
The Schema is as following:
view plainprint?

1. {
2.

"description": "A geographical coordinate",

3.

"type": "object",

4.

"properties": {

5.

"latitude": { "type": "number" },

6.

"longitude": { "type": "number" }

7.

8. }
9.

Calendar
This schema is for microformat style representation of an event. The Schema is as following:
view plainprint?

1. {
2.

"description": "A representation of an event",

3.

"type": "object",

4.

"properties": {

5.

"dtstart": {

6.

"format": "date-time",

7.

"type": "string",

8.

"description": "Event starting time",

9.

"required": true

10.

},

11.

"dtend": {

12.

"format": "date-time",

13.

"type": "string",

14.

"description": "Event ending time"

15.

},

16.

"summary": { "type": "string", "required": true },

17.

"location": { "type": "string" },

18.

"url": { "type": "string", "format": "uri" },

19.

"duration": {

20.

"format": "time",

21.

"type": "string",

22.

"description": "Event duration"

23.

},

24.

"rdate": {

25.

"format": "date-time",

26.

"type": "string",

27.

"description": "Recurrence date"

28.

},

29.

"rrule": {

30.

"type": "string",

31.

"description": "Recurrence rule"

32.

},

33.

"category": { "type": "string" },

34.

"description": { "type": "string" },

35.

"geo": { "$ref": "http: //json-schema.org/geo" }

36.

37. }
38.

Address
This schema is for microformat style representation of an address. The Schema is as following:
view plainprint?

1. {
2.

"description": "An Address following the convention of http://microformats.org/


wiki/hcard",

3.

"type":"object",

4.

"properties": {

5.

"post-office-box": { "type": "string" },

6.

"extended-address": { "type": "string" },

7.

"street-address": { "type": "string" },

8.

"locality":{ "type": "string", "required": true },

9.

"region": { "type": "string", "required": true },

10.

"postal-code": { "type": "string" },

11.

"country-name": { "type": "string", "required": true}

12.

},

13.

"dependencies": {

14.

"post-office-box": "street-address",

15.
16.

"extended-address": "street-address"
}

17. }
18.
These are the Schemas available for mow, since this project is in the process of being updated, keep
watching for more Schemas to come. By that time you may explore these schemas to validate your
JSON objects and let us know what you reveal.
photo credit: mayhem via photopin cc

<<PreviousNext>>

- See more at: http://www.w3resource.com/JSON/JSON-Schema.php#sthash.A4BOP60c.dpuf

You might also like