JSON

From Wikipedia, the free encyclopedia

JSON (JavaScript Object Notation) is a lightweight computer data interchange format. It is a text-based, human-readable format for representing objects and other data structures and is mainly used to transmit such structured data over a network connection (in a process called serialization).

JSON finds its main application in Ajax web application programming, as a simple alternative to using XML for asynchronously transmitting structured information between client and server.

JSON is a subset of the object literal notation of JavaScript and is commonly used with that language. However the basic types and data structures of most other programming languages can also be represented in JSON, and the format can therefore be used to exchange structured data between programs written in different languages. Code for parsing and generating JSON (the latter is also known as "stringifying") is available for the following languages: ActionScript, C, C++, C#, ColdFusion, Common Lisp, Delphi/Object pascal, E, Erlang, Haskell, Java, JavaScript, Limbo, Lua, ML, Objective-C, Objective CAML, Perl, PHP, Python, Rebol, Ruby, Smalltalk and Tcl.

In December 2005, Yahoo! began offering some of its Web Services optionally in JSON.[1]. Google started offering JSON feeds for its GData web protocol in December 2006.[2]

Contents

[edit] Name and specifications

JSON stands for "JavaScript Object Notation" and is pronounced like the English given name Jason, IPA /dʒeɪsən/).

JSON is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999 [3]. The format is specified in RFC 4627 by Douglas Crockford. The official MIME Media Type for JSON is application/json.

[edit] Supported data types, syntax and example

JSON's basic types are

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 732-1234",
        "646 123-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.

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;
    }
};
http_request.send(null);

Note that the use of XMLHttpRequest in this example is not cross-browser; syntactic variations are available on 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 on the same host that served the current page.

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

[edit] eval()

As mentioned above, if JSON data does not come from a trusted source it should be processed with a parser, not with the eval() function.

[edit] Cross-site request forgery

Naïve deployments of JSON are subject to cross-site request forgery attacks (CSRF or XSRF)[4]. Because the <script> tag does not respect the same origin policy, a malicious page can request JSON data belonging to another site; this will cause the JSON 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. (Although the JSON data, as an object literal, would normally evaluate to a constant and so not be visible to the attacker, by overriding the Array() prototype the attacker can feed the JSON data through their own parser.)

The simplest fix for this attack is to wrap the JSON in a multi-line comment (/* ... */) to prevent it being evaluated when referenced from a <script> tag; the comments of course need to be removed prior to parsing by the legitimate site; this will not work if the attack uses an <iframe>. Alternatives include magic cookie methods (but not HTTP cookies, since these will be sent by the browser as usual). A supplementary fix is to set the web server to refuse to serve JSON when the correct referer is not provided; this could however cause problems with clients that have been configured not to send referer information.

[edit] Comparison with other formats

[edit] XML

XML is often used to describe structured data and to serialize objects. XML is however a markup language and is thus significantly more complex than JSON, which is specifically designed as a data interchange format, not a markup language. Both lack a rich mechanism for representing large binary data types such as image data.

[edit] Other simplified markup languages

[edit] References

[edit] External links

  • www.json.org: the specification, documentation, and implementation of JSON readers and writers for numerous programming languages.
  • RFC 4627, formal specification
  • ChaNT - Demonstration of Json work in ligament with Ajax and PHP.

[edit] Tutorials

[edit] Other