JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition – December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.
JSON is built on two structures:
- A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
- An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
Note: JSON is not JavaScript; It is a subset of JavaScript.
Syntax
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": {
"home": "212 555-1234",
"fax": "646 555-4567"
}
}
The equivalent for the above in XML:
21 2nd Street
New York
NY
10021
212 555-1234
212 555-1234
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.
In general, eval() should only be used to parse JSON if the source of the JSON-formatted text is completely trusted; the execution of untrusted code is obviously dangerous. JSON parsers are available to process JSON input from less trusted sources.
References:




