JSON

JSON, short for JavaScript Object Notation, is a lightweight computer data interchange format. It is a text-based, human-readable format for representing simple data structures and associative arrays (called objects).

The JSON format is specified in RFC 4627 by Douglas Crockford. The official Internet media type for JSON is. The JSON filename extension is.

The JSON format is often used for serialization and transmitting structured data over a network connection. Its main application is in Ajax web application programming, where it serves as an alternative to the XML format.

Although JSON was based on a subset of the JavaScript programming language (specifically, Standard ECMA-262 3rd Edition—December 1999 ) and is commonly used with that language, it is considered to be a language-independent data format. Code for parsing and generating JSON data is readily available for a large variety of programming languages. The json.org website provides a comprehensive listing of existing JSON bindings, organized by language.

In December 2005, Yahoo! began offering some of its web services optionally in JSON. Google started offering JSON feeds for its GData web protocol in December 2006.

Data types, syntax and example
JSON's basic types are:


 * Number (integer, real, or floating point)
 * String (double-quoted Unicode with backslash escaping)
 * Boolean ( and  )
 * Array (an ordered sequence of values, comma-separated and enclosed in square brackets)
 * Object (collection of key:value pairs, comma-separated and enclosed in curly braces)

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). The equivalent for the above in XML: Suppose the above text is contained in the JavaScript string variable. Since JSON is a subset of JavaScript's object literal notation, one can then recreate the object describing John Smith with a simple : In build json parsers are now available in advanced browsers, like Firefox 3.5 and IE 8.0. and the fields,  ,   etc. are then accessible. The  variable must be wrapped in parentheses to avoid an ambiguity in JavaScript's syntax.

In general,  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. A JSON parser will recognize only JSON text, rejecting all scripts. In browsers that provide native JSON support, JSON parsers are also much faster than eval. It is expected that native JSON support will be included in the next ECMAScript standard. 

JSON Schema
There are several ways to verify the structure and data types inside a JSON object, much like an XML schema. JSON Schema is a specification for a JSON-based format for defining the structure of JSON data. JSON Schema provides a contract for what JSON data is required for a given application and how it can be modified, much like what XML Schema provides for XML. JSON Schema is intended to provide validation, documentation, and interaction control of JSON data. JSON Schema is based on the concepts from XML Schema, RelaxNG, and Kwalify, but is intended to be JSON-based, so that JSON data in the form of a schema can be used to validate JSON data, the same serialization/deserialization tools can be used for the schema and data, and it can be self descriptive.

Using JSON in Ajax
The following JavaScript code shows how the client can use an XMLHttpRequest to request an object in JSON format from the server. (The server-side programming is omitted; it has to be set up to respond to requests at  with a JSON-formatted string.) Note that the use of XMLHttpRequest in this example is not cross-browser compatible; syntactic variations are available for Internet Explorer, Opera, Safari, and Mozilla-based browsers. The usefulness of XMLHttpRequest is limited by the same origin policy: the URL replying to the request must reside within the same DNS domain as the server that hosts the page containing the request. Alternatively, the JSONP approach incorporates the use of an encoded callback function passed between the client and server to allow the client to load JSON-encoded data from third-party domains and to notify the caller function upon completion, although this imposes some security risks and additional requirements upon the server.

Browsers can also use  elements to asynchronously request JSON data in a cross-browser fashion, or use simple   submissions. These approaches were prevalent prior to the advent of widespread support for XMLHttpRequest.

Dynamic  tags can also be used to transport JSON data. With this technique it is possible to get around the same origin policy but it is insecure. JSONRequest has been proposed as a safer alternative.

Security issues
Although JSON is intended as a data serialization format, its design as a subset of the JavaScript programming language poses several security concerns. These concerns center on the use of a JavaScript interpreter to dynamically execute JSON text as JavaScript, thus exposing a program to errant or malicious script contained therein—often a chief concern when dealing with data retrieved from the internet. While not the only way to process JSON, it is an easy and popular technique, stemming from JSON's design to be compatible with JavaScript's eval function, and illustrated by the following code examples.

JavaScript
Because all JSON-formatted text is also syntactically legal JavaScript code, an easy way for a JavaScript program to parse JSON-formatted data is to use the built-in JavaScript  function, which was designed to evaluate JavaScript expressions. Rather than using a JSON-specific parser, the JavaScript interpreter itself is used to execute the JSON data to produce native JavaScript objects.

The 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. Also, such breaches of trust may create vulnerabilities for data theft, authentication forgery, and other potential misuse of data and resources. RFC 4627 which defines JSON suggests using the following code to validate JSON before eval'ing it (the variable 'text' is the input JSON): The application/json Media Type for JavaScript Object Notation (JSON) A new function,, has been proposed as a safer alternative to  , as it is specifically intended to process JSON data and not JavaScript. It was to be included in the Fourth Edition of the ECMAScript standard, though it is available now as a JavaScript library at http://www.JSON.org/json2.js and will be in the Fifth Edition of ECMAScript.

Native JSON
Recent web browsers now either have or are working on native JSON encoding/decoding which removes the  security problem above. Native JSON is generally faster compared to the JavaScript libraries commonly used before. As of June 2009 the following browsers have or will have native JSON support:


 * Mozilla Firefox 3.5+
 * Microsoft Internet Explorer 8
 * Webkit-based browsers (eg. Google Chrome, Apple Safari)

At least 3 popular JavaScript libraries have committed to use native JSON if available:


 * jQuery
 * Dojo Toolkit
 * mootools

XML
XML is often used to describe structured data and to serialize objects. Various XML-based protocols exist to represent the same kind of data structures as JSON for the same kind of data interchange purposes. However, XML being a general purpose markup language, they are syntactically more complex and bigger in file size than JSON, which, in contrast, is specifically designed for data interchange. Both lack an explicit mechanism for representing large binary data types such as image data (although binary data can be serialized in either case by applying a general purpose binary-to-text encoding scheme).

YAML
Both functionally and syntactically, JSON is effectively a subset of YAML. The common YAML library (Syck) also parses JSON. Prior to YAML version 1.2, JSON was not quite a perfect subset, primarily because YAML lacked native handling of UTF-32 and required comma separators to be followed by a space.

The most distinguishing point of comparison is that YAML offers the following syntax enrichments which have no corresponding expression in JSON:

Relational:
YAML offers syntax for relational data: rather than repeating identical data later in a document, a YAML document can refer to an anchor earlier in the file/stream. Recursive structures (for example, an array containing itself) can be expressed this way. For example, a film data base might list actors (and their attributes) under a Movie's cast, and also list Movies (and their attributes) under an Actor's portfolio.

Extensible:
YAML also offers extensible data types beyond primitives (i.e., strings, floats, ints, bools) which can include class-type declarations.

Blocks:
YAML uses a block-indent syntax to allow formatting of structured data without use of additional characters (ie: braces, brackets, quotation marks, etc.). Besides giving YAML a different appearance than JSON, this block-indent device permits the encapsulation of text from other markup languages or even JSON in the other languages native literal style and without escaping of colliding sigils.

Efficiency
JSON is primarily used for communicating data over the Internet, but has certain characteristics which limit its efficiency for this purpose. In particular, decoding must be done on a character-by-character basis, and the standard has no provision for data compression, interning of strings, or object references.

JSONP
JSONP or "JSON with padding" is a JSON extension wherein a prefix is specified as an input argument of the call itself. This padding prefix is typically the name of a callback function, but may also be a variable assignment, an if statement, or any other Javascript statement prefix. The original proposition appears to have been made in the MacPython blog in 2005 and is now used by many Web 2.0 applications such as Dojo Toolkit Applications, Google Toolkit Applications and Web Services. Further extensions of this protocol have been proposed by considering additional input arguments as, for example, is the case of JSONPP supported by S3DB web services.

Because JSONP makes use of script tags, calls are essentially open to the world. For that reason, JSONP may be inappropriate to carry sensitive data.

Including script tags from remote sites allows the remote sites to inject any content into a website. If the remote sites have vulnerabilities that allow JavaScript injection, the original site can also be affected.

Cross-site request forgery
Naïve deployments of JSONP are subject to cross-site request forgery attacks (CSRF or XSRF). Because the HTML  tag does not respect the same origin policy in web browser implementations, a malicious page can request and obtain JSON data belonging to another site. This will allow the JSON-encoded data to be evaluated in the context of the malicious page, possibly divulging passwords or other sensitive data if the user is currently logged into the other site.

This is only a problem if the JSON-encoded data contains sensitive information that should not be disclosed to a third party, and the server depends on the browser's Same Origin Policy to block the delivery of the data in the case of an improper request. There is no problem if the server determines the propriety of the request itself, only putting the data on the wire if the request is proper. Cookies are not by themselves adequate for determining if a request was authorized. Exclusive use of cookies is subject to cross-site request forgery.

Object references
The JSON standard does not support object references, but the Dojo Toolkit illustrates how conventions can be adopted to support such references using standard JSON. Specifically, the dojox.json.ref module provides support for several forms of referencing including circular, multiple, inter-message, and lazy referencing.