JSON Tutorial,definition, history, usage and Comparison

Introduction to JSON

This page introduces you to JSON – JavaScript Object Notation. We have discussed definition, history, usage and Comparison with XML of JSON in this page.

What is JSON

JSON is a lightweight text-based open standard data-interchange format.

You can read and write JSON easily.

JSON is derived from a subset of JavaScript programming language (Standard ECMA-262 3rd Edition—December 1999).

It is entirely language independent and can be used with most of the modern programming languages.

JSON files are saved with .json extension.

Internet media type of JSON is “application/json”.

A simple example of JSON

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

The above example shows information about three students – their name and major subjects are stored using JSON.

Though you need to read and understand JSON structures to understand the concept of JSON better, the following image may help you to understand the concept of JSON a little better.

understanding JOSN

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.

Various Web Services and APIs use JSON format to provide public data. Using the associated Service / API, you can fetch that data and use it to create applications.

For example, if you click this link, you would get user information about ‘logicum_co’ in twitter and last two tweets of the user.

If you look the available data closely you will see meaningful information in a very structured way.
JSON format (or a close derivative of that) is used by various NoSQL databases to store data. For example MongoDb, CoucheDB uses JSON format to store data.

This is a simple document (as record in SQL) stored in MongoDB. MongoDB uses BSON (a derivative of JSON) format to store data.

FirstName=”Arun”, Address=”St. Xavier’s Road”, Spouse=[{Name:”Kiran”}], Children=[{Name:”Rihit”, Age:8}].
FirstName=”Sameer”,Address=”8 Gandhi Road”.

Comparison with XML

Since both JSON and XML are mean to be a data interchange format, there is always a comparison between JSON and XML.

The similarity between them lies in the points that, both of them are plain text, human readable and can be used with most of the modern programming languages.

But unlike XML, JSON supports data structures (name/value pairs and ordered list of values) which are universal in nature and supported by most of the modern programming languages in some form or other. Which makes JSON more comprehensible, easy to get started with (because you already know the format if you familiar with one or more modern programming languages) and thus easy to use.

Experiences of developers say that JSON is faster that XML.

XML is redundant in nature. Unlike JSON.

What you will learn in webfunda JSON tutorial

Structure and datatypes of JSON.

Working with JSON and PHP.

Working with JSON and JavaScript.

After reading this tutorial, you will gain knowledge to use JSON in practice..

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
b Backspace
f form feed
n newline
r Carriage return
t Horizontal tab
u 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.

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.

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

mysql to JSON

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

php mysql display as json

JSON Document

{“emp_info”:[[“Rameshwar Ghosh”,”rameshwar@example.com”],[“Bidhan Chatterjee”,”bidhan@example.com”],[“Rebati Banerjee”,”rebati@example.com”]]}

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”:[]}.

Description

In this page you will learn about installing JSON in PHP and about PHP json_decode() function with realworld 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 array upon using json_decode function.
depth Integer Specifies recursion depth. This is user specified.
Options Integer Bitmask of JSON decode. As of this writing, only JSON_BIGINT_AS_STRING is supported.

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 10 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(“https://api.twitter.com/1/statuses/user_timeline/logicum_co.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 Logicum_co with the user name of your choice.

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, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, 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

json encode

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 incorrect encoding.
JSON_ERROR_SYNTAX Indicates that this is a syntax error.
JSON_ERROR_UTF8 Indicates that error occurred due to malformed UTF-8 characters, which usually happens because of 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

json_last_error-function-output w3resource

Working with JSON and JavaScript

Discription

In this page you will learn about working with JSON and JavaScript.

1) Loop through json object with javascript

<script type=”text/javascript”>
var test={‘fname’:’Logicum’,’lname’:’Lname’,’profession’:’Blog’,’location’:’USA’,’job-city’:’California’,’frnd-fname’:’wissam’,’frnd-lname’:’wissam’};
for(var k in test)
{
alert(test[k]);
}
</script>

2) Loop through json array with javascript

<script type=”text/javascript”>
var tes={‘friends’:[{‘fname’:’nishant’,’lname’:’garg’},{‘fname’:’nishant’,’lname’:’garg1′},{‘fname’:’nishant’,’lname’:’garg2′},{‘fname’:’nishant’,’lname’:’garg3′}],’abc’:’def’};
for(var i=0;i<tes.friends.length;i++)
{
for(var k in tes.friends[i])
{
alert(tes.friends[i][k]);
}
}

</script>

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.

Leave a Reply