As we have already seen, XML is frequently used to transport data across the web between server and client. However, it is not the only transport format available to us. JSON - JavaScript Object Notation is another format which uses JavaScript syntax to represent data.
To fully understand JSON, it is necessary to have a basic understanding of JavaScript array and object syntax. We have already looked at JavaScript arrays, but another way of initialising a regular array in JavaScript (which we have not covered yet) is to use the square brackets [ and ] as follows to initialise all values at once:
var monthLengths = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];We can also quickly set up objects with curly brackets { and }. Here is how:
var obama = {
"name": 'Barack Obama',
"dob": '4/8/61',
"nationality": 'US'
};
This creates an object representing Barack Obama, with three attributes
name, dob and nationality.
We can
then access the individual attributes of the object using the dot notation, e.g
alert (obama.name + ' ' + obama.dob + ' ' + obama.nationality);will display an alert box reading:
Barack Obama 8/4/61 US
We can combine arrays and objects, to, for example, set up an array of objects, e.g:
var famousPeople = [
{
"name": 'Barack Obama',
"dob": '4/8/61',
"nationality": 'US'
},
{
"name": 'Madonna',
"dob": '16/8/58',
"nationality": 'US'
},
{
"name": 'Noel Gallagher',
"dob": '29/5/67',
"nationality": 'UK'
}
];
This would create an array of three objects representing famous people,
each with name, dob and nationality attributes. (Note that in JavaScript,
objects are dynamic so we can create an array of objects of different
types). We could loop through this array as follows:
for(var i=0; i<famousPeople.length; i++)
{
alert(famousPeople[i].name + ' ' + famousPeople[i].dob + ' '
+ famousPeople[i].nationality);
}
JSON uses standard JavaScript array and object notation to transfer data across the web. Here is an example of some data representing a series of students in JSON. Note how it relates to standard JavaScript array and object syntax:
[
{
"name": "Tim Smith",
"username": "ts282",
"course": "Computer Studies"
},
{
"name": "Jamie Bailey",
"username": "jb139",
"course": "Computer Studies"
},
{
"name": "Deep Patel",
"username": "dp061",
"course": "Networks and Web Design"
}
]
It should therefore be apparent that the JSON example above represents an array (square brackets [ and ] ) of objects (curly brackets { and } ) representing students. It is an array with three members, and each member is a student object with name, username and course attributes.
JSON is most commonly used in conjunction with AJAX. An AJAX application can make a request to a server side script which generates JSON from the contents of a database, and then interpret the JSON returned: this is particularly easy as JSON is valid JavaScript code, so it is simple to parse from JavaScript using eval(). eval() is a function which takes a string of JavaScript and evaluates it. For example:
function responseReceived(xmlHTTP)
{
var data=eval(xmlHTTP.responseText);
// .. do something with the data ..
}
where xmlHTTP.responseText is the text sent back from the web service, i.e. the
JSON code.
However using eval() is somewhat dangerous as it makes the AJAX client vulnerable to exploitation from cross-site scripting attacks. So instead, it is safer to use the Prototype method evalJSON(). evalJSON() makes various safety checks on the JSON returned from the server, to ensure that it does not contain malicious code. Here is an example :
function responseReceived(xmlHTTP)
{
var data=xmlHTTP.responseText.evalJSON();
// .. do something with the data ..
}
In this example, the JSON code is loaded into the variable data. The
variable data will contain whatever data structure is described in the JSON.
So if we load the JSON in the above example into the variable data, the
variable data will contain
an array of 3 student objects. We can access each object
just like ordinary JavaScript objects, e.g.
alert(data[0].name + ' ' + data[0].course + ' ' + data[0].username);would display
Tim Smith Computer Studies ts282We could also loop through all the data, e.g:
for (var i=0; i<data.length; i++)
{
alert(data[i].name + ' ' + data[i].course + ' ' + data[i].username);
}
JSON can be generated server-side in the same way as XML, i.e. we can dynamically generate the JSON from a set of database results. However, the syntax of JSON makes this a bit more awkward to do compared to XML. Luckily PHP (v5.2.0 onwards) provides a function, json_encode(), to automatically generate JSON from PHP arrays or associative arrays (see the DFTI website for more on associative arrays). Here is an example to generate JSON from a PHP array:
$monthLengths = array ( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); echo json_encode($monthLengths);This will produce the JSON:
[ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ]
Here is an example showing an associative array:
$obama = array ("name" => "Barack Obama",
"age" => 46,
"nationality" => "US",
"job" => "President" );
echo json_encode($obama);
This would give the JSON:
{"name" : "Barack Obama", "age" : 46, "nationality" : "US", "job": "President"}
and finally here is an example showing an array of associative arrays:
$students = array (
array ("name" => "Tim Smith",
"username" => "ts282",
"course" => "Computer Studies" ),
array ("name" => "Jamie Bailey",
"username" => "jb139",
"course" => "Computer Studies" ),
array ("name" => "Deep Patel",
"username" => "dp061",
"course" => "Networks and Web Design" )
);
echo json_encode($students);
This will produce the JSON code from the first example, under
What is the format
of JSON?, above. The rule is that
PHP arrays will map to JSON/JavaScript arrays, and PHP associative arrays will
map to JSON/JavaScript objects.
The JSON output from server-side applications should be given a content type of application/json; this will enable clients to recognise the content as JSON. However, by default, Firefox will not recognise JSON: therefore, you will not be able to easily test out a server-side script which generates JSON using the browser. To enable Firefox to recognise JSON you should install the JSONView plugin, available here. This will format the JSON nicely in the browser as long as the content type has been set correctly, e.g. in PHP:
header("Content-type: application/json");
You should only do this exercise if you have completed the basic exercises from Topic 6 (cURL and SAX) and Topic 7 (REST).