From Seo Wiki - Search Engine Optimization and Programming Languages

Jump to: navigation, search
Filename extension .json
Internet media type application/json
Type of format Data interchange
Extended from JavaScript
Standard(s) RFC 4627
Website http://json.org

JSON, short for JavaScript Object Notation, and pronounced "ˈdʒeɪsʌn'", 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 was originally specified in RFC 4627 by Douglas Crockford. The official Internet media type for JSON is application/json. The JSON filename extension is .json.

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[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]


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 (an array) of phone number objects.

     "firstName": "John",
     "lastName": "Smith",
     "age": 25,
     "address": {
         "streetAddress": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "postalCode": "10021"
     "phoneNumbers": [
         { "type": "home", "number": "212 555-1234" },
         { "type": "fax", "number": "646 555-4567" }
     "newSubscription": false,
     "companyName": null

A possible equivalent for the above in XML could be:

<Person firstName="John" lastName="Smith">
    <streetAddress>21 2nd Street</streetAddress>
    <city>New York</city>
  <phoneNumber type="home">212 555-1234</phoneNumber>
  <phoneNumber type="fax">646 555-4567</phoneNumber>
  <companyName />

Per the RFC, the mime-type to be used when transferring a JSON file using HTTP is application/json.

Since JSON is a subset of JavaScript it is possible, but not recommended, to parse the JSON text into an object by invoking JavaScript's eval() function. For example, assume the above JSON text segment is contained in the JavaScript string variable contact. Creating a JavaScript object, p, from the JSON data could be done with the statement:

 var p = eval("(" + contact + ")");

The contact variable must be wrapped in parentheses to avoid an ambiguity in JavaScript's syntax.[4]

The recommended way, however, is to use a JSON parser. Parsers are now built into advanced browsers like Firefox 3.5 and IE 8.0.

  var p = JSON.parse(contact);

The parsed data fields are accessible using standard JavaScript syntax: p.firstName, p.address.city, p.phoneNumbers[0] etc.

Unless you absolutely trust the source of the text, and you have a need to parse and accept text that is not strictly JSON-compliant, you should avoid eval() and use JSON.parse() or another JSON-specific parser instead. A JSON parser will recognize only JSON text and will reject other text, which could contain malevolent JavaScript. 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. [1]

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.[5]

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 && http_request.status == 200 ) {
            the_object = JSON.parse( http_request.responseText );

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 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 eval()

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 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 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 eval. Also, such breaches of trust may create vulnerabilities for data theft, authentication forgery, and other potential misuse of data and resources. The RFC that defines JSON (RFC 4627) suggests using the following code to validate JSON before eval'ing it (the variable 'text' is the input JSON):[6]

var my_JSON_object = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
text.replace(/"(\\.|[^"\\])*"/g, ''))) &&
eval('(' + text + ')');

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 was to be included in the Fourth Edition of the ECMAScript standard,[7] 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.[citation needed]

Native JSON

Recent web browsers now either have or are working on native JSON encoding/decoding which removes the eval() 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:

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

Comparison with other formats


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). JSON lacks references (something XML has via extensions like XLink and XPointer) and has no standard path notation comparable to XPath.


Both functionally and syntactically, YAML is effectively a superset of JSON.[15] The common YAML library (Syck) also parses JSON.[16] Prior to YAML version 1.2, YAML was not quite a perfect superset of JSON, primarily because it 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:

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.
YAML also offers extensible data types beyond primitives (i.e., strings, floats, ints, bools) which can include class-type declarations.
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.


JSON is primarily used for communicating data over the Internet, but has certain characteristics that may limit its efficiency for this purpose. Most of the limitations are general limitations of textual data formats and also apply to XML and YAML. For example, 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. Compression can, of course, be applied to the JSON formatted data.

In practice performance can be comparable to that of similar binary data formats and often depends more on implementation quality than on the theoretical limitations of formats.


JSONP or "JSON with padding" is a complement to the base JSON data format, a usage pattern that allows a page to request and more meaningfully use JSON from a server other than the primary server.

Under the same origin policy, a web page served from domain1.com cannot normally connect to or communicate with a server other than domain1.com. The exception is HTML <script> tags, which can retrieve data from locations other than domain1.com. Taking advantage of the open policy for <script> tags, some pages use them to retrieve JSON from other origins. Without JSONP, a script URL that returns JSON just embeds a data statement into a browser page. In other words, the browser would receive something like:


... which may be interesting but is just data, and has no externally detectable effect in the browser's execution context when received and evaluated.

With JSONP, the browser provides a Javascript prefix to the server; by convention, the browser provides the prefix as a named query string argument in its request to the server, e.g.,

    <script type='text/javascript' src='http://domain1.com/getjson?jsonp=parseResponse'>

The server then wraps its JSON response with this prefix, or "padding", before sending it to the browser. When the browser receives the wrapped response from the server it is now a script, rather than simply a data declaration. In this example, what is received is


...which can cause a change of state within the browser's execution context, because it invokes a method.

While the padding (prefix) is typically the name of a callback function that is defined within the execution context of the browser, it may also be a variable assignment, an if statement, or any other Javascript statement prefix.

The original proposal for JSONP appears to have been made by Bob Ippolito in 2005 [17] and is now used by many Web 2.0 applications such as Dojo Toolkit Applications, Google Web Toolkit Applications[18] and Web Services. Further extensions of this protocol have been proposed by considering additional input arguments as, for example, is the case of JSONPP[19] 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.[20]

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).[21] 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.

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.[22]

See also


  1. Crockford, Douglas (May 28, 2009). "Introducing JSON". json.org. http://json.org. Retrieved July 3, 2009. 
  2. Yahoo!. "Using JSON with Yahoo! Web services". http://developer.yahoo.com/common/json.html. Retrieved July 3, 2009. 
  3. Google. "Using JSON with Google Data APIs". http://code.google.com/apis/gdata/json.html. Retrieved July 3, 2009. 
  4. Crockford, Douglas (July 9, 2008). "JSON in JavaScript". json.org. http://www.json.org/js.html. Retrieved September 8, 2008. 
  5. Turchetto, Matteo; Viklund, Andreas (2007). "JSON Schema Proposal". json.com. http://www.json.com/json-schema-proposal/. Retrieved July 3, 2009. 
  6. Douglas Crockford (July 2006). "IANA Considerations". The application/json Media Type for JavaScript Object Notation (JSON). IETF. sec. 6. RFC 4627. http://tools.ietf.org/html/rfc4627#section-6. Retrieved October 21, 2009. 
  7. Crockford, Douglas (December 6, 2006). "JSON: The Fat-Free Alternative to XML". http://www.json.org/fatfree.html. Retrieved July 3, 2009. 
  8. "Using Native JSON". June 30, 2009. https://developer.mozilla.org/en/Using_JSON_in_Firefox. Retrieved July 3, 2009. 
  9. Barsan, Corneliu (September 10, 2008). "Native JSON in IE8". http://blogs.msdn.com/ie/archive/2008/09/10/native-json-in-ie8.aspx. Retrieved July 3, 2009. 
  10. Hunt, Oliver (June 22, 2009). "Implement ES 3.1 JSON object". https://bugs.webkit.org/show_bug.cgi?id=20031. Retrieved July 3, 2009. 
  11. "YUI 2: JSON utility". September 1, 2009. http://developer.yahoo.com/yui/json/#native. Retrieved October 22, 2009. 
  12. "Ticket #4429". May 22, 2009. http://dev.jquery.com/ticket/4429. Retrieved July 3, 2009. 
  13. "Ticket #8111". June 15, 2009. http://trac.dojotoolkit.org/ticket/8111. Retrieved July 3, 2009. 
  14. "Ticket 419". October 11, 2008. https://mootools.lighthouseapp.com/projects/2706/tickets/419-use-the-native-json-object-if-available. Retrieved July 3, 2009. 
  15. Ben-Kiki, Oren; Evans, Clark; döt Net, Ingy (May 13, 2008). "YAML Ain’t Markup Language (YAML) Version 1.2". http://yaml.org/spec/1.2/#id2560236. Retrieved July 3, 2009. "YAML can therefore be viewed as a natural superset of JSON, offering improved human readability and a more complete information model. This is also the case in practice; every JSON file is also a valid YAML file. This makes it easy to migrate from JSON to YAML if/when the additional features are required." 
  16. RedHanded (April 7, 2005). "YAML is JSON". http://redhanded.hobix.com/inspect/yamlIsJson.html. Retrieved July 3, 2009. 
  17. "Remote JSON - JSONP". from __future__ import *. Bob.pythonmac.org. December 5, 2005. http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/. Retrieved September 8, 2008. 
  18. "GWT Tutorial: How to Read Web Services Client-Side with JSONP". Google Web Toolkit Applications. February 6, 2008. http://www.gwtapps.com/?p=42. Retrieved July 3, 2009. 
  19. Almeida, Jonas (June 11, 2008). "JSON, JSONP, JSONPP?". S3DB. http://sites.google.com/a/s3db.org/s3db/documentation/mis/json-jsonp-jsonpp. Retrieved April 26, 2009. 
  20. RIAspot. "JSON P for Cross Site XHR". http://www.riaspot.com/blogs/entry/JSONP-for-Cross-Site-XHR. [dead link]
  21. Grossman, Jeremiah (January 27, 2006). "Advanced Web Attack Techniques using GMail". http://jeremiahgrossman.blogspot.com/2006/01/advanced-web-attack-techniques-using.html. Retrieved July 3, 2009. 
  22. Zyp, Kris (June 17, 2008). "JSON referencing in Dojo". http://www.sitepen.com/blog/2008/06/17/json-referencing-in-dojo. Retrieved July 3, 2009. 

External links

cs:JavaScript Object Notation de:JavaScript Object Notation es:JSON fr:JavaScript Object Notation ko:JSON id:JSON it:JSON he:JSON lv:JSON nl:JSON ja:JavaScript Object Notation no:JSON pl:JSON pt:JSON ro:JSON ru:JSON fi:JSON sv:JSON ta:யேசண் th:เจซอน tr:JSON uk:JSON zh:JSON

Personal tools

Served in 1.075 secs.