JSON
From Wikipedia, the free encyclopedia
JSON 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#, ColdFusion, Common Lisp, E, Erlang, Java, JavaScript, Lua, ML, Objective CAML, Perl, PHP, Python, Rebol, Ruby, and Tcl.
In December 2005, Yahoo! began offering some of its Web Services optionally in JSON.[1]
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 [2]. The format is specified in RFC 4627. The official MIME Media Type for JSON is application/json
.
[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, commas 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": { "city": "New York, NY", "zipCode": 10021, "streetAddress": "21 2nd Street" }, "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.
A similar technique works in Python, since JSON also happens to be a subset of that language. 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 with eval()
is obviously dangerous. JSON parsers are available to process JSON input from less trusted sources.
[edit] Using JSON in Ajax
The following 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 derive 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)[3]. 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 vulnerable 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 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. 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] YAML
Some of the limitations of JSON are addressed by the data interchange format YAML. Although YAML is significantly more complex[4] than JSON, it is still significantly simpler than XML.
It has been observed that JSON is a nearly functional subset of YAML[5]. YAML parsers can be used to handle most of JSON. This occurred by coincidence and not by design; YAML and JSON were conceived mostly in isolation of each other.
[edit] Other simplified markup languages
[edit] References
- ^ Yahoo!. Using JSON with Yahoo! Web services.
- ^ Introducing JSON. json.org.
- ^ Advanced Web Attack Techniques using GMail – Jeremiah Grossman, WhiteHat Security
- ^ http://bob.pythonmac.org/archives/2005/07/19/what-happened-to-yaml/ What happened to YAML?
- ^ http://redhanded.hobix.com/inspect/yamlIsJson.html
[edit] External links
- www.json.org: the specification, documentation, and implementation of JSON readers and writers for numerous programming languages.
- RFC 4627, formal specification
[edit] Tutorials
- AJAX without XML Compares using XML, JavaScript Objects, and JSON
- Speeding Up AJAX with JSON Demos how it is easier to reference JSON rather than XML.
- JSON AJAX Chat Tutorial Simple tutorial that shows how to create a dynamic web chat
- JSON/AJAX/PHP Simple tutorial and code libraries
[edit] Other
- JSON Discussion Group
- JSON-RPC
- Relationship between JSON and YAML
- Ajax.NET Professional library to export .NET classes into JSON syntax and enable AJAX styled web applications + stand-alone JSON parser
- Json.NET a .NET JSON API for reading, writing and serializing .NET objects to and from JSON
- Jayrock implementation of JSON and JSON-RPC for the Microsoft .NET Framework.
- SimpleJSON a simple and fast implementation of JSON for Python.
- JSON: The Fat-Free Alternative to XML
- JSONTools Java toolset to handle JSON streams.