Home | About | Web Stories | View All Posts

12 Jul 2014

What is a json File Why its so popular

JSON is an easier and logical way of format for collecting and interchanging data. It is lightweight and alternative of XML.It can be read and used by any programming language due to its 'text-based format'.

JSON full form -  JavaScript Object Notation

JSON full form - What is full form of JSON?

The full form of JSON is - JavaScript Object Notation

What is JSON file?

The file in which we store the JSON data is called the JSON file. ".json" is used as JSON filename extension and "application/json" is used as MIME type for JSON text. The JSON file example name is - "abcdfilename.json"

Is JSON the same as JavaScript?

The JSON format is syntactically identical to the code for creating JavaScript objects. Because of this similarity, a JavaScript program can easily convert JSON data into native JavaScript objects. The JSON syntax is derived from the JavaScript object notation syntax, but the JSON format is text only.

Syntax of JSON Data

There are several guidelines that must follow the JSON syntax rules such as - Data is in name/value pairs, Data is separated by commas, Curly brackets contain objects, Square brackets contain fields. Below are examples with explanation -

JSON Data is written in name/value pairs format separated by ,(comma). For example -
"author": "Aashutosh Kumar Yadav"

JSON Object literal is written in Curly braces. JSON Object literals can store multiple name/values pairs. For example -
{ "id":"0001", "Book Name": "First World", "author": "Aashutosh Kumar Yadav" }

Arrays is written in Square brackets. Array can store multiple JSON Object literals. For example -
[{ "id":"0001", "Book Name": "First World", "author": "Aashutosh Kumar Yadav" }, { "id":"0002", "Book Name": "Second World", "author": "Aashutosh Kumar Yadav" }]

JSON object literal and JavaScript Objects

An object literal is when you declare an object in your JavaScript code, which is a variable that stores data in key-value pairs, while JSON stands for JavaScript Object Notation and is a language-agnostic format for storing and transferring data that is based on JavaScript objects.

You would use object literals in your code when you need to create an object such as a user profile so you can read and write its properties later, or when working with classes.

JSON is used when you want to store data and transfer it across different platforms and programming languages. One easy way to recognize JSON is to see that its property names are always enclosed in quotes like below -
{ "Book Name": "First World", "author": "Aashutosh Kumar Yadav" }

While object literals do not use quotes for property names like below -
let bookCollections = { Book Name: "First World", author: "Aashutosh Kumar Yadav" };

You'll often see JSON data stored as a separate file from the JavaScript havign file extension as (.json), while object literals appear directly in the JavaScript code itself.

Storing and accessing JSON data

  • Normal Format -
    Here is an example JSON data, for manager detail. In this example, we have created an object using the variable "manager" in which we have created properties with a name-value pair separated by commas. It means we are storing different values of a manager.
    var manager = {
    "name" : "Aashutosh"
    "age" : "44",
    "gender" : "male"
    };

    To access the data stored in the manager object, we only need to use the property name. To get information about the manager, the following code is used -
    document.write('Manager name is ' manager.name); // Output: Manager name is Aashutosh
    document.write('Manager age is ' manager.age); // Output: Manager age is 44
    document.write('Manger gender is ' manager.gender); // Output: Manager gender is male

    The following html code has been tested for getting the JSON object output. You can also check below code snippet after copying the code in html file and run into the browser -

    <!DOCTYPE html>
    <html>
    <body>
    <h2>Access a JSON object</h2>
    <script>
    var manager = {"name" : "Aashutosh", "age" : "44", "gender" : "male"};
    document.write('Manager name is: ' + manager.name + "<br />"); // Output: Manager name is: Aashutosh
    document.write('Manager age is: ' + manager.age + "<br />"); // Output: Manager age is: 44
    document.write('Manager gender is: ' + manager.gender + "<br />"); // Output: Manager gender is: male
    </script>
    </body>
    </html>

  • Array Format -
    When we have to store two people in the same variable then it is difficult but we can do this work easily by using array format. For this we put more than one object in a square bracket which is the standard syntax of array format. For example, to store the information of two managers, the following type of code has to be used -

    var managers = [{
    "name" : "Aashutosh",
    "age" : "44",
    "gender" : "male"
    },
    {
    "name" : "Kishor",
    "age" : "45",
    "gender" : "male"
    }];

    To get information about each manager we need to access the array index of the manager we want to access. For this we use the following code -

    document.write(managers[0].age); // Output: 44
    document.write(managers[1].name); // Output: Kishor

    The following html code has been tested for getting the JSON object with array output. You can also check below code snippet after copying the code in html file and run into the browser -

    <!DOCTYPE html>
    <html>
    <body>
    <h2>Access a JSON object</h2>
    <script>
    const managers = [
    {"name" : "Aashutosh","age" : "44","gender" : "male"},
    {"name" : "Kishor","age" : "45","gender" : "male"}
    ];
    document.write(managers[0].age); // Output: 44
    document.write(managers[1].name); // Output: Kishor
    </script>
    </body>
    </html>

  • Nested Format -
    We can store multiple people in same variable by nesting the objects which has been shown as following codes -
    var managers = {
    "aashutosh" : {
    "name" : "Aashutosh Kumar Yadav",
    "age" : "44",
    "gender" : "male"
    },
    "kyle" : {
    "name" : "Kishore Kumar Jha",
    "age" : "45",
    "gender" : "male"
    }
    }
    We can access the information in nested objects using following code -
    document.write(managers.aashutosh.name); // Output: Aashutosh Kumar Yadav
    document.write(managers.kishore.age); // Output: 45
    document.write(managers.aashutosh.gender); // Output: male

Why JSON is so popular?

With the popularity of AJAX-based websites, the usability and value of the process of loading content data quickly and asynchornoously or in the background without page refresh has become increasingly important.

Many social media based websites like flickr, twitter etc. provide RSS feed to show their content on other site which is easily used on the server side. But when we use it through Ajax then cross domain error comes as - "You can load RSS feed from the same domain it is hosted on".

The cross-domain issue with json is gone forever because we can use a method called JSONP which uses a callback function to send JSON data back to our domain. This powerful capability of Json makes Json incredibly useful and what was previously impossible to do due to errors is now easily accomplished. That is why JSON is most popular in the web development industry.

What is JSON is JSONP - What are the differences between JSON and JSONP?

Full Form of JSONP - JavaScript Object Notation with Padding.

JSONP stands for JSON with padding i.e, you put a string at the beginning and a pair of parentheses around it as like following example -
//JSON format>
{"name":"Aashutosh","id":10009, "rank":101}>
//JSONP format>
funciton_name_for_calling({"name":"Aashutosh","id":10009, "rank":101});>
Thus, JSONP is a json with ability to transmit information or data to another domain, without error. Simply JSONP specifies a type of callback function that is passed to a JSON object. This gives you the ability to bypass the same origin policy and load JSON from an external server into JavaScript on your webpage.

How JSON is loaded into a project

We can use jQuery library inbuilt method - $.ajax() for loading the json data into the web applications. Here the following codes are the very simple example for loading the JSON data via $.ajax() method. This code represents for requesting the latest feed items in JSON format and output them to the browser.

$.ajax(
type:'GET',
url:"http://yourdomainname.com/users/feeds/",
data:"format=json&id=653542",
success:function(feed) {
document.write(feed);
},
dataType:'jsonp'
);

JSON file example

JSON data has been collected of this blog on particular date for showing sample as JSON format. Both formatted and non formatted data sample link has been given below. You can examine way of JSON format in the sample pages.

Click for View Non Formatted JSON sample file

Click for View Formatted JSON sample file

Click for View Non Formatted JSON live file

How to open json file - JSON file viewer, JSON formatter and JSON editor

One can view and edit JSON data at online JSON viewer. JSON viewer tool link is available at JSON official website. One of the best online viewer printshots has been presented below.

It uses two window. One can place JSON non-formatted data in left window. Left window has two small icons(check second and third printshot) to show non-formatted and formatted JSON data with proper indentation and line feeds.

Right window shows formatted JSON data, objects and arrays with total available number. Right window printshot has been given below -


View Full Image


View Full Image


View Full Image

JSON and XML or JSON vs XML

Both are same in many cases like - plain text, human readable and use of HttpRequest etc. But there are differences also like - no use of end tag in JSON, JSON data is shorter and faster to read and write, JSON use arrays etc.

The major difference is JSON uses standard JavaScript function as parser whereas XML uses XML parser.

PHP and JSON

JSON uses PHP 5.2.0 programming environment. JSON extension is already bundled and compiled into PHP 5.2.0

Two function are used for JSON interpretation into PHP - json_encode() for encoding JSON in PHP and json_decode() for decoding JSON in PHP type.

Encoding JSON in PHP using json_encode() function
<?php
$arr = array('Number' => 1, 'Name' => "Your Name", 'Location' => "USA", 'Phone' => 6664, 'Email' => "youremail");
echo json_encode($arr);
?>

OUTPUT(as JSON data) -
{"Number":1,"Name":"Your Name","Location":"USA","Phone":6664,"Email":"youremail"}

Decoding JSON in PHP using json_decode() function
<?php
$json = '{"Number":1,"Name":"Your Name","Location":"USA","Phone":6664,"Email":"youremail"} ';
echo '<pre>';
var_dump(json_decode($json));
echo '</pre>';
echo '<pre>';
var_dump(json_decode($json, true));
echo '</pre>';
?>


OUTPUT(as PHP data) -
object(stdClass)#1 (5) {
["Number"]=>int(1)
["Name"]=>string(9) "Your Name"
["Location"]=>string(3) "USA"
["Phone"]=>int(6664)
["Email"]=>string(9) "youremail"
}
array(5) {
["Number"]=>int(1)
["Name"]=>string(9) "Your Name"
["Location"]=>string(3) "USA"
["Phone"]=>int(6664)
["Email"]=>string(9) "youremail"
}

PHP and Json data with multi-dimensional data or array-
Take a view for this type of multidimentional data in the image below. The field - "Trackinghistory" contains datewise entry list in the image below. We use foreach loop to output the datewise data for these type of json data format.



<?php
$json_data = '{"Number":1,"Name":"Your Name","Location":"USA","Phone":6664,"Email":"youremail", "Trackinghistory":"[{\"id\":1,\"Date\":\"12\/01\/2011\",\"Location\":\"Delhi\", \"Status\":\"Delivered\"},{\"id\":2,\"Date\":\"12\/02\/2011\",\"Location\":\"Delhi\", \"Status\":\"Unavailable\"},{\"id\":3,\"Date\":\"12\/03\/2011\",\"Location\":\"Delhi\", \"Status\":\"In Transit\"}]","messageType":"success"} ';
$json = json_decode($json_data, true);
echo "Number " . $json['Number'];
echo "<br />";
echo "Name ". $json['Name'];
echo "<br />";
echo "Location " . $json['Location'];
echo "<br />";
echo "Phone " . $json['Phone'];
echo "<br />";
echo "Email " . $json['Email'];
echo "<br />";
echo "Tracking History";
echo "<br />";
$json2 = json_decode($json['Trackinghistory'], true);
foreach($json2 as $value) {
echo $value['id'] . "," . $value['Date'] . "," . $value['Location']. "," . $value['Status'];
echo "<br />";
}
?>

Use of JSON - a practical example: "Listing Five recent post of Blog using Blog feed url"

Nowadays JSON is delivering important and useful role in data interchange due to its cross-domain independence i.e. we can send JSON data back to domain using callback function which was never possible before. You have to use "callback" parameter in the url for this. For example -

http://infotokri.blogspot.com/feeds/posts/default?orderby=published&alt=json-in-script&callback=your_callback_function_name

Just place above url in url box of the browser and see what happens. Whole feed output JSON data will be enclosed into 'your_callback_function_name', because you have passed this name as callback parameter.

Following code has been written for displaying five recent post title of this blog using available JSON feed link with callback fuctionality.

Help for verifying JSON data format has been taken by JSON online viewer. Its print screen has been presented below just after code. Colored circle has been drawn for easy visual interpretation. For example blue color for title like "entry.title.$t"

Click here to view output of below code.

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JSON live feed example</title>
<!-- Function should be in first place -->
<script language="javascript" type="text/javascript">
function showrecentposts(json){
//document.write(json.feed);
//document.write(entry);
for (var i = 0; i < 5; i++) {
var entry = json.feed.entry[i];
//document.write(entry.title.$t);
var posttitle = entry.title.$t;
var posturl;
if (i == json.feed.entry.length) break;
for (var k = 0; k < entry.link.length; k++) {
if (entry.link[k].rel == 'alternate') {
posturl = entry.link[k].href;
break;
}
}
posttitle = posttitle.link(posturl);
document.write('

'+posttitle + '

');
}
}
</script>
<!-- Blog available JSON feed link -->
<script type="text/javascript" src="http://infotokri.blogspot.com/feeds/posts/default?alt=json-in-script&amp;callback=showrecentposts"></script>
<!-- Feed link should be in second place or after function -->
</head>
<body>
<script language="javascript" type="text/javascript">
showrecentposts();
</script>
</body>
</html>


Use of JSON - Read Live example

One can view another real world example for "Use of JSON data" at View All Posts page of this blog itself. All posts titles have been listed ordered by published date, using JSON data technique at view all posts link page.
Tags :
Aashutosh Kumar Yadav

By Aashutosh Kumar Yadav

He is a PHP-based UI/Web designer and developer by profession and very interested in technical writing and blogging. He has been writing technical content for about 10 years and has proficient in practical knowledge and technical writing.
@www.infotokri.in

0 comments:

Post a Comment