JSON
From Wikipedia, the free encyclopedia
JSON | |
---|---|
File name extension | .json |
Internet media type | application/json |
Type of format | Data interchange |
JSON (pronounced /ˈdʒeɪsɒn/, i.e., "Jason"), 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 application/json
. The JSON file extension is .json
.
The JSON format is often used for transmitting structured data over a network connection in a process called serialization. Its main application is in Ajax web application programming, where it serves as an alternative to the traditional use of the XML format.
Although JSON was based on a subset of the JavaScript programming language (specifically, Standard ECMA-262 3rd Edition—December 1999[1]) 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.[2] Google started offering JSON feeds for its GData web protocol in December 2006.[3]
Contents |
[edit] Supported data types, syntax and example
JSON's basic types are
- Number (integer, real, or floating point)
- String (double-quoted Unicode with backslash escapement)
- Boolean (
true
andfalse
) - 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 brackets)
null
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 JSON_text
. 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("(" + JSON_text + ")");
and the fields p.firstName
, p.address.city
, p.phoneNumbers[0]
etc. are then accessible. Parentheses are necessary because bare objects are not valid JavaScript.
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.
[edit] 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 url
with a JSON-formatted string.)
var the_object; var http_request = new XMLHttpRequest(); http_request.open( "GET", url, true ); http_request.onreadystatechange = function () { if ( http_request.readyState == 4 ) { if ( http_request.status == 200 ) { the_object = eval( "(" + http_request.responseText + ")" ); } else { alert( "There was a problem with the URL." ); } http_request = null; } };
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 <iframe>
elements to asynchronously request JSON data in a cross-browser fashion, or use simple <form action="url_to_cgi_script" target="name_of_hidden_iframe">
submissions. These approaches were prevalent prior to the advent of widespread support for XMLHttpRequest.
Dynamic <script>
tags can also be used to transport JSON data. With this technique it is possible to get around the overly restrictive same origin policy but it is insecure. JSONRequest has been proposed as a safer alternative.
[edit] 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 preceding code examples.
[edit] JavaScript eval()
Because most 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 eval()
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 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.
A new function, parseJSON()
, has been proposed as a safer alternative to eval
, as it is specifically intended to process JSON data and not JavaScript. It will likely 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
[edit] Cross-site request forgery
Naïve deployments of JSON are subject to cross-site request forgery attacks (CSRF or XSRF).[4] Because the HTML <script>
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.
The solution to this issue is to always send an unadorned object as the outermost container -- that is, the data should start with "{" and end with "}". This data could still be requested by a malicious page, but, since it results in an error when evaluated, it cannot be manipulated in any way, including forwarding it to a third party.[5]
[edit] Comparison with other formats
[edit] XML
XML is often used to describe structured data and to serialize objects. Unlike JSON, however, which is a way to represent data structures, XML is a markup language. This makes XML arguably more complex than JSON, which is specifically designed as a data interchange format, not a markup language. Both lack a rich (i.e., explicit) mechanism for representing large binary data types such as image data (although binary data can be stringified for both by converting to a base64 or similar representation).
[edit] YAML
Both functionally and syntactically, JSON is effectively a subset of YAML. Notably, the most widespread YAML library also parses JSON[6]. Strictly speaking, the syntax is not quite a perfect subset, primarily because YAML lacks native handling of some extended character sets allowed in JSON (e.g. unicode like UTF-32) and requires 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.[7]
- Extensible:
- YAML also offers extensible data types beyond primitives (i.e beyond strings, floats, ints, bools) which can include class-type declarations or Unicode types.
[edit] Accessibility and SEO
JSON+AJAX implementations are affected by significant web accessibility and search engine optimisation issues. The progressive enhancement methodology could be used to mitigate these issues.
[edit] See also
[edit] References
- ^ Introducing JSON. json.org.
- ^ Yahoo!. Using JSON with Yahoo! Web services.
- ^ Google. Using JSON with Google Data APIs.
- ^ Advanced Web Attack Techniques using GMail – Jeremiah Grossman, WhiteHat Security
- ^ Tom Hughes-Croucher. Security; AJAX; JSON; Satisfaction. Note: this is not a general solution to XSRF problems, simply to the additional risks that JSON can bring.
- ^ YAML is JSON, RedHanded, 08 Apr 2005.
- ^ 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.
[edit] External links
- Format home page
- RFC 4627, current formal JSON specification.
- JSONRequest
- Relationship between JSON and YAML
- Ric Johnson's JSON blog
- The Limitations of JSON
- JsonT JSON analog to XSLT
- Yahoo JSON
- JSON Java framework