Tuesday, January 6, 2009

JSON

JSON (JavaScript Object Notation) is a lightweight taxt based data-interchange format. It is based on subset of Javascript standar ECMA-262 3rd Edition.

JSON is built on two structures:

  1. A collection of name/value pairs.
  2. An ordered list of values.
Examples

The following example shows the JSON representation of an object that describes a person. The object has string fields for first name and last name, contains an object representing the person's address, and contains a list of phone numbers (an array).

{
"firstName": "John",
"lastName": "Smith",
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
},
"phoneNumbers": [
"212 555-1234",
"646 555-4567"
]
}

Suppose the above text is contained in the JavaScript string variable contact. Since JSON is a subset of JavaScript's object literal notation, one can then recreate the object describing John Smith with a simple eval():

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

and the fields p.firstName, p.address.city, p.phoneNumbers[0] etc. are then accessible. The contact variable must be wrapped in parentheses to avoid an ambiguity in JavaScript's syntax.

Security issues

eval technique is subject to security vulnerabilities if the data and the entire JavaScript environment is not within the control of a single trusted source. If the data is itself not trusted, for example, it may be subject to malicious JavaScript code injection attacks; unless some additional means is used to validate the data first. Regular expressions are sometimes used to perform this check prior to invoking eval. Also, such breaches of trust may create vulnerabilities for data theft, authentication forgery, and other potential misuse of data and resources. The RFC that defines JSON suggests using the following code to validate JSON before eval'ing it (the variable 'text' is the input JSON) :

var my_JSON_object = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
text.replace(/"(\\.|[^"\\])*"/g, ''))) &&
eval('(' + text + ')');
Source: www.json.org,http://en.wikipedia.org/wiki/JSON

No comments: