Wednesday, November 5, 2008

JSON - JavaScript Object Notation

JSON is a really cunning text-based data transfer object transfer format. Various basic data types (Strings, ints, etc) can be stored in object relationships. It is intended (used?) as a 'lightweight' alternative to XML, which tends to be heavy and wordy.

Example:

JSON format:
{
"firstName": "John",
"lastName": "Smith",
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
},
"phoneNumbers": [
"212 555-1234",
"646 555-4567"
]
}
In JavaScript, an object can be created of this as follows:

var p = eval('(' + contact + ')');

In JavaScript, the object attributes can be accessed as follows:

p.firstName, p.address.city, p.phoneNumbers[0]


It appears that use of schemas is possible but somehow outside the core JSON vibe. Care must be taken to ensure that dangerous js code is not inserted into the JSON string, which would be executed with the eval() statement.

In PHP:



$popups = array();

$popups[] = 'This is the first popup';
$popups[] = 'This is the second popup';

$return['popups'] = $popups;
$return['result'] = 'success';

// output correct header
$isXmlHttpRequest = (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) ?
(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') ? true : false: false;
($isXmlHttpRequest) ? header('Content-type: application/json') : header('Content-type: text/plain');

echo json_encode($return);
?>



This info summarised from the kindly Wikipedia: http://en.wikipedia.org/wiki/JSONP#JSONP


No comments: