JavaScript Object Notation (JSON)
- To read and write object and array literals in JavaScript.
- To use JSON for transferring data between the browser and server.
JSON is a lightweight format for exchanging data between the client and server. It is often used in Ajax applications because of its simplicity and because its format is based on JavaScript object literals. We will start this lesson by learning JavaScript's object-literal syntax and then we will see how we can use JSON in an Ajax application.
Object Literals
We saw earlier how to create new objects in JavaScript with the Object() constructor. We also saw how we could create our constructors for our own objects. In this lesson, we'll examine JavaScript's literal syntax for creating arrays and objects.
Arrays
Array literals are created with square brackets as shown below:
var Beatles = ["Paul","John","George","Ringo"];
This is the equivalent of:
var Beatles = new Array("Paul","John","George","Ringo");Objects
Object literals are created with curly brackets:
var Beatles = {
"Country" : "England",
"YearFormed" : 1959,
"Style" : "Rock'n'Roll"
}This is the equivalent of:
var Beatles = new Object(); Beatles.Country = "England"; Beatles.YearFormed = 1959; Beatles.Style = "Rock'n'Roll";
Just as with all objects in JavaScript, the properties can be references using dot notation or bracket notation.
alert(Beatles.Style); //Dot Notation alert(Beatles["Style"]); //Bracket Notation
Arrays in Objects
Object literals can contain array literals:
var Beatles = {
"Country" : "England",
"YearFormed" : 1959,
"Style" : "Rock'n'Roll",
"Members" : ["Paul","John","George","Ringo"]
}Objects in Arrays
Array literals can contain object literals:
var Rockbands = [
{
"Name" : "Beatles",
"Country" : "England",
"YearFormed" : 1959,
"Style" : "Rock'n'Roll",
"Members" : ["Paul","John","George","Ringo"]
},
{
"Name" : "Rolling Stones",
"Country" : "England",
"YearFormed" : 1962,
"Style" : "Rock'n'Roll",
"Members" : ["Mick","Keith","Charlie","Bill"]
}
]JSON
On the JSON website (http://www.json.org), JSON is described as:
- a lightweight data-interchange format
- easy for humans to read and write
- easy for machines to parse and generate
Numbers 1 and 3 are certainly true. Number 2 depends on the type of human. Experienced programmers will find that they can get comfortable with the syntax relatively quickly.
JSON Syntax
The JSON syntax is like JavaScript's object literal syntax except that the objects cannot be assigned to a variable. JSON just represents the data itself. So, the Beatles object we saw earlier would be defined as follows:
{
"Name" : "Beatles",
"Country" : "England",
"YearFormed" : 1959,
"Style" : "Rock'n'Roll",
"Members" : ["Paul","John","George","Ringo"]
}JSON Parsers
As JSON is just a string of text and not an object in and of itself, it needs to be converted to an object before to make it useful. Although this can be done in JavaScript with the eval() function, it is safer to use a JSON parser. You can download the JavaScript JSON parser at http://www.json.org/json.js. Including this file on a web page allows you to take advantage of the JSON object, which has the following very useful methods:
- JSON.parse(strJSON) - converts a JSON string into a JavaScript object.
- JSON.stringify(objJSON) - converts a JavaScript object into a JSON string.
The process for sending data between the browser and server with JSON is as follows:
- On the client-side:
- Create a JavaScript object using the standard or literal syntax.
- Use the JSON parser to stringify the object.
- Send the URL-encoded JSON string to the server as part of the HTTP Request. This can be done using the HEAD, GET or POST method by assigning the JSON string to a variable. It can also be sent as raw text using the POST method, but this may create extra work for you on the server-side.
- On the server-side:
- Decode the incoming JSON string and convert the result to an object using a JSON parser for the language of your choice. At http://www.json.org, you'll find JSON parsers for many modern programming languages. The methods available depend upon which parser you are using. See the parser's documentation for details.
- Do whatever you wish with the object.
- If you wish to send JSON back to the client:
- Create a new object for storing the response data.
- Convert the new object to a string using your JSON parser.
- Send the JSON string back to the client as the response body (e.g, Response.Write(strJSON), echo $strJSON, out.write(strJSON) etc.).
- On the client-side:
- Convert the incoming JSON string to an object using the JavaScript JSON parser.
- Do whatever you wish with the object.
- And so on...
The examples below show how to transfer data to the server using JSON.
Code Sample: JSON/Demos/SendJson.html
<html>
<head>
<script type="text/javascript" src="../../prototype.js"></script>
<script type="text/javascript" src="../../json.js"></script>
<script type="text/javascript">
function SendRequest(MSG)
{
document.getElementById("ResponseDiv").innerHTML="";
var objJSON = {
"msg" : MSG
};
var strJSON = encodeURIComponent(JSON.stringify(objJSON));
new Ajax.Request("ReceiveJSON.jsp",
{
method: "post",
parameters: "strJSON=" + strJSON,
onComplete: Respond
});
}
function Respond(REQ)
{
document.getElementById("ResponseDiv").innerHTML=REQ.responseText;
}
</script>
<title>Using JSON</title>
</head>
<body>
<h1>Request</h1>
<form>
<input type="button" value="Hi There!" onClick="SendRequest(this.value)"/>
<input type="button" value="Good bye!" onClick="SendRequest(this.value)" />
</form>
<h1>Response</h1>
<div id="ResponseDiv">Waiting...</div>
</body>
</html>
Code Sample: JSON/Demos/ReceiveJSON.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" import="java.net.*,org.json.simple.*"%>
<%
try
{
URLDecoder decoder = new URLDecoder();
String strJSON = decoder.decode(request.getParameter("strJSON"));
JSONObject objJSON = (JSONObject) JSONValue.parse(strJSON);
String Message = objJSON.get("msg").toString();
if (Message.equals("Hi There!"))
{
out.write("And hi there to you!");
}
else
{
out.write("Later Gator!");
}
}
catch (Exception e)
{
out.write(e.toString());
}
%>
This code is relatively simple. The client-side script:
- creates a simple JSON object with one property holding the passed in MSG string.
- converts the JSON object to a string and encodes it.
- passes the string as a parameter of our Ajax request (using Prototype).
- outputs the responseText to the page.
The server-side script:
- decodes the passed in string and converts it to a JSON object.
- outputs an appropriate response.
JSON Advantages and Disadvantages
Advantages
JavaScript Syntax
The fact that JSON uses JavaScript syntax is the biggest advantage. It makes it extremely easy to work with on the client side. Compare this to traversing the XML DOM or XSLT and you'll find great efficiencies in working with JSON.
Brevity
Another oft-touted advantage of JSON is that it is lightweight. Compare, for example, the Rockbands object we saw earlier in the lesson in JSON vs. XML:
//JSON
[
{
"Name" : "Beatles",
"Country" : "England",
"YearFormed" : 1959,
"Style" : "Rock'n'Roll",
"Members" : ["Paul","John","George","Ringo"]
},
{
"Name" : "Rolling Stones",
"Country" : "England",
"YearFormed" : 1962,
"Style" : "Rock'n'Roll",
"Members" : ["Mick","Keith","Charlie","Bill"]
}
]
//XML
<Rockbands>
<Rockband>
<Name>Beatles</Name>
<Country>England</Country>
<YearFormed>1959</YearFormed>
<Members>
<Member>Paul</Member>
<Member>John</Member>
<Member>George</Member>
<Member>Ringo</Member>
</Members>
</Rockband>
<Rockband>
<Name>Rolling Stones</Name>
<Country>England</Country>
<YearFormed>1962</YearFormed>
<Members>
<Member>Mick</Member>
<Member>Keith</Member>
<Member>Charlie</Member>
<Member>Bill</Member>
</Members>
</Rockband>
</Rockbands>The XML representation has almost twice as many characters. While for long files, this may be significant, in most cases this will not cause any noticeable difference. Further, if you were to represent the XML with attributes rather than elements, the difference would be much less.
Disadvantages
New Syntax - Not So Human Readable
The biggest disadvantage of working with JSON is it is yet another syntax we need to familiarize ourselves with. However, with a little effort, most developers will find it's not too difficult to get comfortable with.
Not "XPathable"
XPath makes it possible to search through XML documents and find specific node values based on many different criteria (e.g, relative location to other nodes in the document). JavaScript objects and arrays have no comparable built-in capability.
JavaScript Object Notation (JSON) Conclusion
In this lesson of the Ajax tutorial, you have learned how to work with JSON to transfer data to and from the server. As you develop Ajax applications, you'll find JSON an excellent tool to have in your kit.
