1. JSON
JSON stands for JavaScript Object Notation that is a language
independent text format which is fast and easy to understand. That means it
is really very simple and easy to learn without sparing much time. In
another words we can say that JavaScript Object Notation is a lightweight
data-interchange format that is completely language independent but with
some conventions.
Why JSON?
1. Because JSON is easy to write. It is just like creating and accessing
class in javascript in object notation
2. If you like Hash Tables, you will fall in love with JSON.
3. JSON is just key: value pairs assigned within an object.
4. JSON is very fast.
5. It is easy to understand and can be integrated in any web application
very easily.101194
6. Better organized data if prepared in well mannered way.
Creating Objects in JavaScript using JSON:
JSON is syntax for passing around objects that contain name/value pairs,
arrays and other objects.
We can create objects in JSON with JavaScript in many ways:
"var JSONObjectName ={};" will create an empty object.
"var JSONObjectName= new Object();" will create a new Object.
"var JSONObjectName = { "name ":"amit", "age":23}; will
create an Object with attribute name which contains value in String
and age with numeric value.
Now by creating this object we can access attributes by only "." operator.
Squiggles, Squares, Colons and Commas
1. Squiggly brackets act as 'containers'
2. Square brackets holds arrays
3. Names and values are separated by a colon.
4. Array elements are separated by commas
2. Advantages of JSON:
Because JSON was designed for the purpose of serializing and
unserializing data being sent to and from JavaScript applications, the
advantages of using JSON relate to the advantages of JSON over other
means of serialization. The most well-known means of serializing data for
transmission to and from applications at present is XML. Yet, XML is a
rather cumbersome means of serialization.
First, the sender must encode the data to be serialized based on a
document type definition that the recipient understands. Doing so creates a
great deal of extra padding around the actual data no matter which DTD is
used. So, the size of XML documents is often fairly large in comparison with
the actual set of values they contain.
Second, the recipient must receive the stream of XML and decode the
data in order to then put that data into memory. In comparison, the
serialization of data using JSON by the sender is relatively quick and
compact because the structure of JSON reflects the structure of standard
programming data types and the encoding mechanism adds only the
minimum number of characters required to indicate the structure and value
of the data.
Once the recipient receives the JSON serialized data, then, the only
processing needing to be done is to evaluate the text of the string using
either JavaScript's built-in eval function or a compatible function in another
language. The other standard comparison is YAML, which is able to serialize
complex data sets without relying upon a DTD and needs a simpler parser to
both read and write than XML. However, even the simplified YAML parsers
generally require more time and generate larger serialized data streams
than JSON.
JSON is like XML because:
1. They are both 'self-describing' meaning that values are named, and
thus 'human readable'
2. Both are hierarchical. (i.e. you can have values within values.)
3. Both can be parsed and used by lots of programming languages
4. Both can be passed around using AJAX (i.e. httpWebRequest)
3. JSON is Unlike XML because:
1. XML uses angle brackets, with a tag name at the start and end of an
element: JSON uses squiggly brackets with the name only at the
beginning of the element.
2. JSON is less verbose so it's definitely quicker for humans to write, and
probably quicker for us to read.
3. JSON can be parsed trivially using the eval() procedure in JavaScript
4. JSON includes arrays {where each element doesn't have a name of its
own}
5. In XML you can use any name you want for an element, in JSON you
can't use reserved words from javascript
Example: Object creation in JSON in JavaScript
<html>
<head>
<title>
Object creation in JSON in JavaScript
</title>
<script language="javascript" >
var JSONObject = { "name" : "Amit",
"address" : "B-123 Bangalow",
"age" : 23,
"phone" : "011-4565763",
"MobileNo" : 0981100092
};
document.write("<h2><font color='blue'>Name</font>::"
+JSONObject.name+"</h2>");
document.write("<h2><font color='blue'>Address</font>::"
+JSONObject.address+"</h2>");
document.write("<h2><font color='blue'>Age</font>::"
+JSONObject.age+"</h2>");
document.write("<h2><font color='blue'>Phone No.</font>::"
+JSONObject.phone+"</h2>");
document.write("<h2><font color='blue'>Mobile No.</font>::"
+JSONObject.MobileNo+"</h2>");
</script>
</head>
4. <body>
<h3>Example of object creation in JSON in JavaScript</h3>
</body>
</html>
How to use JSON in JQUERY:
You have a JSON file with some information stored in it. You want to
import that information from the JSON file into the current web page
asynchronously. The JSON file is a file that contains information regarding
‘name’ and ‘value’ pairs.
The HTML file should look like this:
<body>
<p>For information from JSON file click the button given below :<br>
<input type="submit" id="submit"/>
<div id="message"></div>
</body>
The JSON file drinkinfo.json have information like this:
[
{"optiontext" : "Tea", "optionvalue" : "Tea"},
{"optiontext" : "Coffee", "optionvalue" : "Coffee"},
{"optiontext" : "Juice", "optionvalue" : "Juice"}
]
This JSON file can be used in the JQUERY like this:
$(document).ready (function () {
$('#submit').click (function () {
$.ajax ({
type:"GET",
url:"drinkinfo.json",
dataType:"json",
success: function (data) {
var drinks="<ul>";
$.each(data, function(i,n){
drinks+="<li>"+n["optiontext"]+"</li>";
});
drinks+="</ul>";
$('#message').append(drinks);
}
});
5. return false;
});
});
The information received in data contains two attributes: optiontext
and optionvalue, and we want to return only the contents of the optiontext
attribute to the web page, in the form of a list. We therefore make use of
the each() method to parse each object stored in data. In the callback
function of each() method, we use two parameters: i and n where i refers to
the index location of the object in data and n refers to object containing
information (in terms of attributes optiontext and optionvalue).
We can also simplify the above jQuery code by making use of the
$.getJSON() method, which is particularly designed for retrieving data from
a JSON file. This method makes a GET request to the specified url address
(on the server), along with its passed parameters, and returns information in
the form of JSON encoded data. Its syntax looks like this:
$.getJSON (url, parameters, callbackfuncton)
And the parameters are:
url is name of the file along with its address on the server
parameters is a string containing information in the form of name and
value pairs to be passed to the url
callback function is the response generated from the server , when the
request succeeds
The jQuery code to use the $.getJSON() method is as shown here, and
it works much the same way as our previous solution but as you can see,
leads to some neater code:
$(document).ready (function () {
$('#submit').click (function () {
$.getJSON ('drinkinfo.json', function (data){
var drinks="<ul>";
$.each (data, function (i,n){
drinks +="<li>"+n ["optiontext"]+"</li>";
});
drinks +="</ul>";
$('#message').append (drinks);
});
return false;
});
});
6. Limitations of JSON:
The most important disadvantage of JSON is that the format is very
hard to read for humans, and that, of course, every single comma, quote,
and bracket should be in exactly the correct place. While this is also true of
XML, JSON's welter of complicated-looking syntax, like the}}]} at the end of
the data snippet, may frighten the newbies and make for complicated
debugging.
JSON shows its greatest weakness. Yes the little semantics JSON data
structures have makes them easy to work with. One knows how to interpret
an array, how to interpret a number and how to interpret a Boolean. But this
is very minimal semantics. It is very much pre web semantics. It works as
long as the client and the server, the publisher of the data and the consumer
of the data are closely tied together. Why so? Because there is no use of
URIs, Universal Names, in JSON. JSON has a provincial semantics. Compare
to XML which gives a place for the concept of a namespace specified in
terms of a URI.