BookRags.com Literature Guides Literature
Guides
Criticism & Essays Criticism &
Essays
Questions & Answers Questions &
Answers
Lesson Plans Lesson
Plans
My Bibliography Periodic Table U.S. Presidents Shakespeare Sonnet Shake-Up
Research Anything:        
History | Encyclopedias | Films | News | Create a Bibliography | More... Login | Register | Help
Not What You Meant?  There are 36 definitions for Jason.

JSON

Print-Friendly
About 6 pages (1,792 words)

Bookmark and Share Know this topic well? Help others and get FREE products!

JSON (JavaScript Object Notation) (pronounced /ˈdʒeɪsən/, like Jason) 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 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

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(): <source lang="javascript">

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

</source> 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.

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.) <source lang="javascript"> 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;
   }

}; </source> 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. 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.

Security issues

JSON is a self-contained unambiguous data representation format, and since it carries no executable or algorithmic meaning, it is inherently secure by itself. Security issues can arise, however, if a program incorrectly processes JSON-formatted data as though it were something else. Since the JSON syntax is, by design, a subset of the JavaScript syntax, most security concerns involve having a JavaScript interpreter directly process JSON text as though it were JavaScript source code.

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. Rather than using a JSON-specific parser, the JavaScript interpreter itself is used to execute the JSON data to produce native JavaScript objects. This technique relies on intentionally misrepresenting the format of the input text as being JavaScript rather than JSON. Using the eval technique can be safe as long as everything, including both the JSON data and the entire JavaScript environment, is within the control of a single trusted source. In a web browser environment, however, this unified trust of all the components does not exist, allowing security to be breached. If the JSON data is itself not trusted, it would be possible to embed rogue JavaScript code inside the supposed JSON data. In addition, if the entire JavaScript environment is not trusted (including all the code loaded into the environment), then it is theoretically possible to intercept the evaluation of the JSON data. The parseJSON method is a safe alternative to eval. It will likely be included in the Fourth Edition of the ECMAScript standard. It is available now as a JavaScript library at http://www.JSON.org/json2.js

Cross-site request forgery

Naive 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. A weak attempt to dodge this class of attacks involves wrapping or otherwise altering the JSON-formatted data so that it cannot be interpreted as valid JavaScript code. For example, wrapping the JSON-formatted text, such as inside a multi-line JavaScript comment (/* ... */), and then unwrapping it before parsing it. This is trivial to circumvent and cannot be considered a security measure. A better method is to send as part of the HTTP request a magic cookie that can identify a legitimate session. This cannot be a HTTP cookie, since these will be sent by the browser as usual. A supplementary defense is to set the web server to refuse to serve JSON when an HTTP referer is different from the trusted site.

Comparison with other formats

XML

XML is often used to describe structured data and to serialize objects. Unlike JSON, however, which is simply a way to represent data structures, XML is a complete markup language. This makes XML more complex than JSON, which is specifically designed as a data interchange format, not a markup language. An XML feature with no corresponding representation in JSON is the concept of a data set being "valid" (i.e. contains all expected content) in addition to simply being "well-formed" (i.e. obeying syntax rules); XML allows a format definition header to determine when a data structure is logically correct and is thus valid. 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).

YAML

Both functionally and syntactically, JSON is effectively a subset of YAML. Notably, the most widespread YAML library also parses JSON[5]. 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.[6]
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
Blocks:
YAML's versatile block-indent syntax allows formatting of structured data in a manner visually uncluttered by quotations, escapes, commas,semicolons, braces and brackets, making it exceptionally human readable. Indeed, this very wiki-subsection is 100% well-formed YAML and resolves to hashmap collection with the indented text strings as the values.[7]

See also

References

  1. ^ Introducing JSON. json.org.
  2. ^ Yahoo!. Using JSON with Yahoo! Web services.
  3. ^ Google. Using JSON with Google Data APIs.
  4. ^ Advanced Web Attack Techniques using GMail – Jeremiah Grossman, WhiteHat Security
  5. ^ YAML is JSON, RedHanded, 08 Apr 2005.
  6. ^ 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.
  7. ^ The keys of the Hashmap shown are "Blocks", "Extensible",and "Relational".

External links

Tutorials

View More Summaries on JSON
 
Ask any question on JSON and get it answered FAST!
Answer questions in BookRags Q&A and earn points toward
discounted or even FREE Study Guides and other BookRags products!
Learn more about BookRags Q&A
Copyrights
JSON from Wíkipedia. ©2006 by Wíkipedia. Licensed under the GNU Free Documentation License. View a list of authors or edit this article.

Article Navigation
Join BookRagslearn moreJoin BookRags




About BookRags | Customer Service | Report an Error | Terms of Use | Privacy Policy