JSON
Encyclopedia
JSON or JavaScript Object Notation, is a lightweight text-based open standard designed for human-readable
data interchange. It is derived from the JavaScript
scripting language for representing simple data structure
s and associative array
s, called objects. Despite its relationship to JavaScript, it is language-independent, with parsers available for most languages.
The JSON format was originally specified by Douglas Crockford
, and is described in RFC 4627. The official Internet media type
for JSON is
The JSON format is often used for serializing
and transmitting structured data over a network connection. It is used primarily to transmit data between a server and web application, serving as an alternative to XML
.
was the first to specify and popularize the JSON format.
JSON was used at State Software, a company co-founded by Crockford, starting around 2001. The JSON.org website was launched in 2002. In December 2005, Yahoo!
began offering some of its web service
s in JSON. Google
started offering JSON feeds for its GData
web protocol in December 2006.
Although JSON was based on a subset of the JavaScript
scripting language
(specifically, Standard ECMA
-262 3rd Edition—December 1999) and is commonly used with that language, it is a language-independent
data format. Code for parsing
and generating JSON data is readily available for a large variety of programming languages. JSON's website provides a comprehensive listing of existing JSON libraries
, organized by language.
Non-significant white space may be added freely around the "structural characters" (i.e. the brackets "[{]}", colon ":" and comma ",").
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, a number field for age, contains an object representing the person's address, and contains a list (an array) of phone number objects.
Since JSON is a subset of JavaScript, it is possible (but not recommended) to parse JSON text into an object by invoking JavaScript's
if the above JSON data is contained within a JavaScript string variable contact, one could use it to create the JavaScript object p like so:
The
The recommended way, however, is to use a JSON parser. Unless a client absolutely trusts the source of the text, or must parse and accept text which is not strictly JSON-compliant, one should avoid
Modern browsers, such as Firefox 4 and Internet Explorer
8, include special features for parsing JSON. As native browser support is more efficient and secure than
standard.
defines several native data types not included in the JSON standard: Date, Error, Math, Regular Expression, and Function. These JavaScript data types must be represented as some other data format, with the programs on both ends agreeing on how to convert between types. As of 2011, there are some defacto standards for e.g. converting between Date and String, but none universally recognized. Other languages may have a different set of native types that must be serialized
carefully to deal with this type of conversion.
however unlike XML schema JSON schemas are not widely used. Additionally JSON Schema have to be written manually, unlike XML there are currently no tools available to generate a JSON schema from JSON data.
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 the 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.
JSON Schema is still an IETF draft, but there are several validators currently available for different programming languages, each with varying levels of conformance. Currently the most complete and compliant JSON Schema validator available is JSV.
Example JSON Schema:
The JSON Schema above can be used to test the validity of the JSON code below:
techniques.
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
var my_JSON_object = {};
var http_request = new XMLHttpRequest;
http_request.open("GET", url, true);
http_request.onreadystatechange = function {
var done = 4, ok = 200;
if (http_request.readyState
my_JSON_object = JSON.parse(http_request.responseText);
}
};
http_request.send(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.
The above javascript
code is used to get Kundapura Wikipedia Page.
Browsers can also use
fashion, or use simple
Dynamic
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.
JavaScript
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
Unless precautions are taken to validate the data first, 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. Also, such breaches of trust may create vulnerabilities for data theft
, authentication forgery
, and other potential misuse of data and resources. Regular expression
s can be used to validate the data prior to invoking
A new function,
standard, but this did not occur. It was first added to the Fifth Edition, and is now supported by the major browsers given below. For older ones, a compatible JavaScript library is available at JSON.org.
At least 5 popular JavaScript libraries have committed to use native JSON if available:
, YAML
and CSV
. Also, Google Protocol Buffers
can fill this role, although it is not a data interchange language.
can be 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. When data is encoded in XML, the result is typically larger in size than an equivalent encoding in JSON, mainly because of XML's closing tags, but if the data is compressed using an algorithm like gzip
there is little difference because compression is good at saving space when a pattern is repeated. There are alternative ways to encode the same information. Both of the following XML examples carry the same information as the JSON example above in different ways.
The XML encoding may therefore be shorter than the equivalent JSON encoding. A wide range of XML processing technologies exist, from the Document Object Model
to XPath
and XSLT
. XML can also be styled for immediate display using CSS
. XHTML
is a form of XML so that elements can be passed in this form ready for direct insertion into webpages using client-side scripting.
for this purpose. Most of the limitations are general limitations of textual data formats and thus also apply to XML
(excepting binary XML
) and YAML
. For example, despite typically being generated by an algorithm (by machine), parsing
must be accomplished on a character-by-character basis. Additionally, 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 (but the decompressed output typically still requires further full parsing for recognizable keyword
s, tag
s and delimiter
s).
, 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.
Human-readable
A human-readable medium or human-readable format is a representation of data or information that can be naturally read by humans.In computing, human-readable data is often encoded as ASCII or Unicode text, rather than presented in a binary representation...
data interchange. It is derived from the JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....
scripting language for representing simple data structure
Data structure
In computer science, a data structure is a particular way of storing and organizing data in a computer so that it can be used efficiently.Different kinds of data structures are suited to different kinds of applications, and some are highly specialized to specific tasks...
s and associative array
Associative array
In computer science, an associative array is an abstract data type composed of a collection of pairs, such that each possible key appears at most once in the collection....
s, called objects. Despite its relationship to JavaScript, it is language-independent, with parsers available for most languages.
The JSON format was originally specified by Douglas Crockford
Douglas Crockford
Douglas Crockford is an American computer programmer and entrepreneur, best known for his ongoing involvement in the development of the JavaScript language, and for having popularized the data format JSON , and for developing JSLint...
, and is described in RFC 4627. The official Internet media type
Internet media type
An Internet media type, originally called a MIME type after MIME and sometimes a Content-type after the name of a header in several protocols whose value is such a type, is a two-part identifier for file formats on the Internet.The identifiers were originally defined in RFC 2046 for use in email...
for JSON is
application/json
. The JSON filename extension is .json
.The JSON format is often used for serializing
Serialization
In computer science, in the context of data storage and transmission, serialization is the process of converting a data structure or object state into a format that can be stored and "resurrected" later in the same or another computer environment...
and transmitting structured data over a network connection. It is used primarily to transmit data between a server and web application, serving as an alternative to XML
XML
Extensible Markup Language is a set of rules for encoding documents in machine-readable form. It is defined in the XML 1.0 Specification produced by the W3C, and several other related specifications, all gratis open standards....
.
History
Douglas CrockfordDouglas Crockford
Douglas Crockford is an American computer programmer and entrepreneur, best known for his ongoing involvement in the development of the JavaScript language, and for having popularized the data format JSON , and for developing JSLint...
was the first to specify and popularize the JSON format.
JSON was used at State Software, a company co-founded by Crockford, starting around 2001. The JSON.org website was launched in 2002. In December 2005, Yahoo!
Yahoo!
Yahoo! Inc. is an American multinational internet corporation headquartered in Sunnyvale, California, United States. The company is perhaps best known for its web portal, search engine , Yahoo! Directory, Yahoo! Mail, Yahoo! News, Yahoo! Groups, Yahoo! Answers, advertising, online mapping ,...
began offering some of its web service
Web service
A Web service is a method of communication between two electronic devices over the web.The W3C defines a "Web service" as "a software system designed to support interoperable machine-to-machine interaction over a network". It has an interface described in a machine-processable format...
s in JSON. Google
Google
Google Inc. is an American multinational public corporation invested in Internet search, cloud computing, and advertising technologies. Google hosts and develops a number of Internet-based services and products, and generates profit primarily from advertising through its AdWords program...
started offering JSON feeds for its GData
GData
GData provides a simple protocol for reading and writing data on the Internet, designed by Google. GData combines common XML-based syndication formats with a feed-publishing system based on the Atom Publishing Protocol, plus some extensions for handling queries. It relies on XML or JSON as a data...
web protocol in December 2006.
Although JSON was based on a subset of the JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....
scripting language
(specifically, Standard ECMA
Ecma International
Ecma International is an international, private non-profit standards organization for information and communication systems. It acquired its name in 1994, when the European Computer Manufacturers Association changed its name to reflect the organization's global reach and activities...
-262 3rd Edition—December 1999) and is commonly used with that language, it is a language-independent
Language-independent specification
A language-independent specification is a programming language specification providing a common interface usable for defining semantics applicable toward arbitrary language bindings. LISs are language-agnostic...
data format. Code for parsing
Parsing
In computer science and linguistics, parsing, or, more formally, syntactic analysis, is the process of analyzing a text, made of a sequence of tokens , to determine its grammatical structure with respect to a given formal grammar...
and generating JSON data is readily available for a large variety of programming languages. JSON's website provides a comprehensive listing of existing JSON libraries
Language binding
In computing, a binding from a programming language to a library or OS service is an API providing that service in the language.Many software libraries are written in systems programming languages such as C or C++...
, organized by language.
Data types, syntax and example
JSON's basic types are:- Number (type not specified, but in practice double precision floating-point format, as this is how JavaScript in Web browsers treats it)
- StringString (computer science)In formal languages, which are used in mathematical logic and theoretical computer science, a string is a finite sequence of symbols that are chosen from a set or alphabet....
(double-quoted UnicodeUnicodeUnicode is a computing industry standard for the consistent encoding, representation and handling of text expressed in most of the world's writing systems...
(UTF-8 by default), with backslash escapingEscape characterIn computing and telecommunication, an escape character is a character which invokes an alternative interpretation on subsequent characters in a character sequence. An escape character is a particular case of metacharacters...
) - BooleanBoolean datatypeIn computer science, the Boolean or logical data type is a data type, having two values , intended to represent the truth values of logic and Boolean algebra...
(true
orfalse
) - Array (an ordered sequence of values, comma-separated and enclosed in square brackets; the values do not need to be of the same type)
- ObjectAssociative arrayIn computer science, an associative array is an abstract data type composed of a collection of pairs, such that each possible key appears at most once in the collection....
(an unordered collection of key:value pairs with the ':' character separating the key and the value, comma-separated and enclosed in curly braces; the keys must be strings and should be distinct from each other) -
null
(empty)
Non-significant white space may be added freely around the "structural characters" (i.e. the brackets "[{]}", colon ":" and comma ",").
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, a number field for age, contains an object representing the person's address, and contains a list (an array) of phone number objects.
Since JSON is a subset of JavaScript, it is possible (but not recommended) to parse JSON text into an object by invoking JavaScript's
evalEvalIn some programming languages, eval is a function which evaluates a string as though it were an expression and returns a result; in others, it executes multiple lines of code as though they had been included instead of the line including the eval...
function. For example,if the above JSON data is contained within a JavaScript string variable contact, one could use it to create the JavaScript object p like so:
The
contact
variable must be wrapped in parentheses to avoid an ambiguity in JavaScript's syntax.The recommended way, however, is to use a JSON parser. Unless a client absolutely trusts the source of the text, or must parse and accept text which is not strictly JSON-compliant, one should avoid
eval
. A correctly implemented JSON parser will accept only valid JSON, preventing potentially malicious code from running.Modern browsers, such as Firefox 4 and Internet Explorer
Internet Explorer
Windows Internet Explorer is a series of graphical web browsers developed by Microsoft and included as part of the Microsoft Windows line of operating systems, starting in 1995. It was first released as part of the add-on package Plus! for Windows 95 that year...
8, include special features for parsing JSON. As native browser support is more efficient and secure than
eval
, native JSON support is included in the recently-released Edition 5 of the ECMAScriptECMAScript
ECMAScript is the scripting language standardized by Ecma International in the ECMA-262 specification and ISO/IEC 16262. The language is widely used for client-side scripting on the web, in the form of several well-known dialects such as JavaScript, JScript, and ActionScript.- History :JavaScript...
standard.
Unsupported native data types
JavaScript syntaxJavaScript syntax
The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program.The examples below make use of the alert function for standard text output. The JavaScript standard library lacks an official standard text output function...
defines several native data types not included in the JSON standard: Date, Error, Math, Regular Expression, and Function. These JavaScript data types must be represented as some other data format, with the programs on both ends agreeing on how to convert between types. As of 2011, there are some defacto standards for e.g. converting between Date and String, but none universally recognized. Other languages may have a different set of native types that must be serialized
Serialization
In computer science, in the context of data storage and transmission, serialization is the process of converting a data structure or object state into a format that can be stored and "resurrected" later in the same or another computer environment...
carefully to deal with this type of conversion.
Schema
There are several ways to verify the structure and data types inside a JSON object, much like an XML schemaXML schema
An XML schema is a description of a type of XML document, typically expressed in terms of constraints on the structure and content of documents of that type, above and beyond the basic syntactical constraints imposed by XML itself...
however unlike XML schema JSON schemas are not widely used. Additionally JSON Schema have to be written manually, unlike XML there are currently no tools available to generate a JSON schema from JSON data.
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 the 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.
JSON Schema is still an IETF draft, but there are several validators currently available for different programming languages, each with varying levels of conformance. Currently the most complete and compliant JSON Schema validator available is JSV.
Example JSON Schema:
The JSON Schema above can be used to test the validity of the JSON code below:
Use in Ajax
JSON is often used in AjaxAjax (programming)
Ajax is a group of interrelated web development methods used on the client-side to create asynchronous web applications...
techniques.
The following JavaScript code shows how the client can use an XMLHttpRequest
XMLHttpRequest
XMLHttpRequest is an API available in web browser scripting languages such as JavaScript. It is used to send HTTP or HTTPS requests directly to a web server and load the server response data directly back into the script. The data might be received from the server as XML text or as plain text...
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 my_JSON_object = {};
var http_request = new XMLHttpRequest;
http_request.open("GET", url, true);
http_request.onreadystatechange = function {
var done = 4, ok = 200;
if (http_request.readyState
done && http_request.status
ok) {my_JSON_object = JSON.parse(http_request.responseText);
}
};
http_request.send(null);
Note that the use of XMLHttpRequest
XMLHttpRequest
XMLHttpRequest is an API available in web browser scripting languages such as JavaScript. It is used to send HTTP or HTTPS requests directly to a web server and load the server response data directly back into the script. The data might be received from the server as XML text or as plain text...
in this example is not cross-browser
Cross-browser
Cross-browser refers to the ability for a website, web application, HTML construct or client-side script to support all the web browsers. The term cross-browser is often confused with multi-browser...
compatible; syntactic
Syntax
In linguistics, syntax is the study of the principles and rules for constructing phrases and sentences in natural languages....
variations are available for Internet Explorer
Internet Explorer
Windows Internet Explorer is a series of graphical web browsers developed by Microsoft and included as part of the Microsoft Windows line of operating systems, starting in 1995. It was first released as part of the add-on package Plus! for Windows 95 that year...
, Opera
Opera (web browser)
Opera is a web browser and Internet suite developed by Opera Software with over 200 million users worldwide. The browser handles common Internet-related tasks such as displaying web sites, sending and receiving e-mail messages, managing contacts, chatting on IRC, downloading files via BitTorrent,...
, Safari
Safari (web browser)
Safari is a web browser developed by Apple Inc. and included with the Mac OS X and iOS operating systems. First released as a public beta on January 7, 2003 on the company's Mac OS X operating system, it became Apple's default browser beginning with Mac OS X v10.3 "Panther". Safari is also the...
, and Mozilla
Mozilla
Mozilla is a term used in a number of ways in relation to the Mozilla.org project and the Mozilla Foundation, their defunct commercial predecessor Netscape Communications Corporation, and their related application software....
-based browsers. The usefulness of XMLHttpRequest is limited by the same origin policy
Same origin policy
In computing, the same origin policy is an important security concept for a number of browser-side programming languages, such as JavaScript. The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but...
: 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
JSONP
JSONP or "JSON with padding" is a complement to the base JavaScript Object Notation JSON data format, a pattern of usage allowing a page to request data from a server in a different domain...
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.
The above javascript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....
code is used to get Kundapura Wikipedia Page.
Browsers can also use
<iframeIFrameiFrame can be:* I-frames, in video compression; see video compression picture types* iFrame * The HTML iframe element....
>
elements to asynchronously request JSON data in a cross-browserCross-browser
Cross-browser refers to the ability for a website, web application, HTML construct or client-side script to support all the web browsers. The term cross-browser is often confused with multi-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>
HTML element
An HTML element is an individual component of an HTML document. HTML documents are composed of a tree of HTML elements and other nodes, such as text nodes. Each element can have attributes specified. Elements can also have content, including other elements and text. HTML elements represent...
tags can also be used to transport JSON data. With this technique it is possible to get around the same origin policy
Same origin policy
In computing, the same origin policy is an important security concept for a number of browser-side programming languages, such as JavaScript. The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but...
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 scripting language poses several security concerns. These concerns center on the use of a JavaScript interpreter to execute JSON text dynamically 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 compatibility with JavaScript's eval function, and illustrated by the following code examples.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. However, there are some Unicode characters that are valid in JSON strings but invalid in JavaScript, so additional escaping would be needed before using a JavaScript interpreter.Unless precautions are taken to validate the data first, the eval technique is subject to security vulnerabilities
Vulnerability (computing)
In computer security, a vulnerability is a weakness which allows an attacker to reduce a system's information assurance.Vulnerability is the intersection of three elements: a system susceptibility or flaw, attacker access to the flaw, and attacker capability to exploit the flaw...
if the data and the entire JavaScript environment is not within the control of a single trusted source
Trusted system
In the security engineering subspecialty of computer science, a trusted system is a system that is relied upon to a specified extent to enforce a specified security policy...
. If the data is itself not trusted, for example, it may be subject to malicious JavaScript code injection
Code injection
Code injection is the exploitation of a computer bug that is caused by processing invalid data. Code injection can be used by an attacker to introduce code into a computer program to change the course of execution. The results of a code injection attack can be disastrous...
attacks. Also, such breaches of trust may create vulnerabilities for data theft
Data theft
Data theft is a growing problem primarily perpetrated by office workers with access to technology such as desktop computers and hand-held devices capable of storing digital information such as USB flash drives, iPods and even digital cameras...
, authentication forgery
Digital identity
Digital identity is the aspect of digital technology that is concerned with the mediation of people's experience of their own identity and the identity of other people and things...
, and other potential misuse of data and resources. Regular expression
Regular expression
In computing, a regular expression provides a concise and flexible means for "matching" strings of text, such as particular characters, words, or patterns of characters. Abbreviations for "regular expression" include "regex" and "regexp"...
s can be used to validate the data prior to invoking
eval
. For example, 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):A new function,
JSON.parse
, was developed as a safer alternative to eval
. It is specifically intended to process JSON data and not JavaScript. It was originally planned for inclusion in the Fourth Edition of the ECMAScriptECMAScript
ECMAScript is the scripting language standardized by Ecma International in the ECMA-262 specification and ISO/IEC 16262. The language is widely used for client-side scripting on the web, in the form of several well-known dialects such as JavaScript, JScript, and ActionScript.- History :JavaScript...
standard, but this did not occur. It was first added to the Fifth Edition, and is now supported by the major browsers given below. For older ones, a compatible JavaScript library is available at JSON.org.
Native encoding and decoding in browsers
Recent Web browsers now either have or are working on native JSON encoding/decoding. This removes theeval
security problem above and also makes it faster because it doesn't parse functions. 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, via JSON.parse
and JSON.stringify
:- Mozilla Firefox 3.5Mozilla Firefox 3.5Mozilla Firefox 3.5 is a version of the Firefox web browser released in June 2009, adding a variety of new features to Firefox. Version 3.5 was touted as being twice as fast as 3.0...
+ - Microsoft Internet ExplorerInternet ExplorerWindows Internet Explorer is a series of graphical web browsers developed by Microsoft and included as part of the Microsoft Windows line of operating systems, starting in 1995. It was first released as part of the add-on package Plus! for Windows 95 that year...
8 - Opera 10.5Opera (web browser)Opera is a web browser and Internet suite developed by Opera Software with over 200 million users worldwide. The browser handles common Internet-related tasks such as displaying web sites, sending and receiving e-mail messages, managing contacts, chatting on IRC, downloading files via BitTorrent,...
+ - WebkitWebKitWebKit is a layout engine designed to allow web browsers to render web pages. WebKit powers Google Chrome and Apple Safari and by October 2011 held over 33% of the browser market share between them. It is also used as the basis for the experimental browser included with the Amazon Kindle ebook...
-based browsers (e.g. Google Chrome, Apple Safari)
At least 5 popular JavaScript libraries have committed to use native JSON if available:
- YUI Library
- PrototypePrototype Javascript FrameworkThe Prototype JavaScript Framework is a JavaScript framework created by Sam Stephenson in February 2005 as part of the foundation for Ajax support in Ruby on Rails. It is implemented as a single file of JavaScript code, usually named prototype.js...
- jQueryJQueryjQuery is a cross-browser JavaScript library designed to simplify the client-side scripting of HTML. It was released in January 2006 at BarCamp NYC by John Resig...
- Dojo ToolkitDojo ToolkitDojo Toolkit is an open source modular JavaScript library designed to ease the rapid development of cross-platform, JavaScript/Ajax-based applications and web sites. It was started by Alex Russell, Dylan Schiemann, David Schontzler, and others in 2004 and is dual-licensed under the modified BSD...
- mootoolsMooToolsMooTools is a lightweight, object-oriented, web-application framework for JavaScript, written in JavaScript. It is released under the free, open-source MIT License...
Comparison with other formats
JSON is promoted as a low-overhead alternative to XML as both of these formats have widespread support for creation, reading and decoding in the real-world situations where they are commonly used. Apart from XML, examples could include OGDLOGDL
OGDL , is a "structured textual format that represents information in the form of graphs, where the nodes are strings and the arcs or edges are spaces or indentation."...
, YAML
YAML
YAML is a human-readable data serialization format that takes concepts from programming languages such as C, Perl, and Python, and ideas from XML and the data format of electronic mail . YAML was first proposed by Clark Evans in 2001, who designed it together with Ingy döt Net and Oren Ben-Kiki...
and CSV
Comma-separated values
A comma-separated values file stores tabular data in plain-text form. As a result, such a file is easily human-readable ....
. Also, Google Protocol Buffers
Protocol Buffers
Protocol Buffers are a serialization format with an interface description language developed by Google. The original Google implementation for C++, Java and Python is available under a free software, open source license....
can fill this role, although it is not a data interchange language.
XML
XMLXML
Extensible Markup Language is a set of rules for encoding documents in machine-readable form. It is defined in the XML 1.0 Specification produced by the W3C, and several other related specifications, all gratis open standards....
can be 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. When data is encoded in XML, the result is typically larger in size than an equivalent encoding in JSON, mainly because of XML's closing tags, but if the data is compressed using an algorithm like gzip
Gzip
Gzip is any of several software applications used for file compression and decompression. The term usually refers to the GNU Project's implementation, "gzip" standing for GNU zip. It is based on the DEFLATE algorithm, which is a combination of Lempel-Ziv and Huffman coding...
there is little difference because compression is good at saving space when a pattern is repeated. There are alternative ways to encode the same information. Both of the following XML examples carry the same information as the JSON example above in different ways.
The XML encoding may therefore be shorter than the equivalent JSON encoding. A wide range of XML processing technologies exist, from the Document Object Model
Document Object Model
The Document Object Model is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Aspects of the DOM may be addressed and manipulated within the syntax of the programming language in use...
to XPath
XPath
XPath is a language for selecting nodes from an XML document. In addition, XPath may be used to compute values from the content of an XML document...
and XSLT
XSLT
XSLT is a declarative, XML-based language used for the transformation of XML documents. The original document is not changed; rather, a new document is created based on the content of an existing one. The new document may be serialized by the processor in standard XML syntax or in another format,...
. XML can also be styled for immediate display using CSS
Cascading Style Sheets
Cascading Style Sheets is a style sheet language used to describe the presentation semantics of a document written in a markup language...
. XHTML
XHTML
XHTML is a family of XML markup languages that mirror or extend versions of the widely-used Hypertext Markup Language , the language in which web pages are written....
is a form of XML so that elements can be passed in this form ready for direct insertion into webpages using client-side scripting.
Efficiency
JSON is used primarily for communicating data over the Internet, but has certain inherent characteristics that may limit its efficiencyAlgorithmic efficiency
In computer science, efficiency is used to describe properties of an algorithm relating to how much of various types of resources it consumes. Algorithmic efficiency can be thought of as analogous to engineering productivity for a repeating or continuous process, where the goal is to reduce...
for this purpose. Most of the limitations are general limitations of textual data formats and thus also apply to XML
XML
Extensible Markup Language is a set of rules for encoding documents in machine-readable form. It is defined in the XML 1.0 Specification produced by the W3C, and several other related specifications, all gratis open standards....
(excepting binary XML
Binary XML
Binary XML refers to any specification which defines the compact representation of XML in a binary format. While there are several competing formats, none has been widely adopted by a standards organization or accepted as a de facto standard...
) and YAML
YAML
YAML is a human-readable data serialization format that takes concepts from programming languages such as C, Perl, and Python, and ideas from XML and the data format of electronic mail . YAML was first proposed by Clark Evans in 2001, who designed it together with Ingy döt Net and Oren Ben-Kiki...
. For example, despite typically being generated by an algorithm (by machine), parsing
Parsing
In computer science and linguistics, parsing, or, more formally, syntactic analysis, is the process of analyzing a text, made of a sequence of tokens , to determine its grammatical structure with respect to a given formal grammar...
must be accomplished on a character-by-character basis. Additionally, the standard has no provision for data compression
Data compression
In computer science and information theory, data compression, source coding or bit-rate reduction is the process of encoding information using fewer bits than the original representation would use....
, interning of strings, or object references. Compression can, of course, be applied to the JSON formatted data (but the decompressed output typically still requires further full parsing for recognizable keyword
Keyword (computer programming)
In computer programming, a keyword is a word or identifier that has a particular meaning to the programming language. The meaning of keywords — and, indeed, the meaning of the notion of keyword — differs widely from language to language....
s, tag
HTML element
An HTML element is an individual component of an HTML document. HTML documents are composed of a tree of HTML elements and other nodes, such as text nodes. Each element can have attributes specified. Elements can also have content, including other elements and text. HTML elements represent...
s and delimiter
Delimiter
A delimiter is a sequence of one or more characters used to specify the boundary between separate, independent regions in plain text or other data streams. An example of a delimiter is the comma character, which acts as a field delimiter in a sequence of comma-separated values.Delimiters represent...
s).
Object references
The JSON standard does not support object referencesReference (computer science)
In computer science, a reference is a value that enables a program to indirectly access a particular data item, such as a variable or a record, in the computer's memory or in some other storage device. The reference is said to refer to the data item, and accessing those data is called...
, but the Dojo Toolkit
Dojo Toolkit
Dojo Toolkit is an open source modular JavaScript library designed to ease the rapid development of cross-platform, JavaScript/Ajax-based applications and web sites. It was started by Alex Russell, Dylan Schiemann, David Schontzler, and others in 2004 and is dual-licensed under the modified BSD...
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
Circular reference
A circular reference is a series of references where the last object references the first, resulting in a closed loop.-In language:A circular reference is not to be confused with the logical fallacy of a circular argument...
, multiple, inter-message, and lazy
Lazy evaluation
In programming language theory, lazy evaluation or call-by-need is an evaluation strategy which delays the evaluation of an expression until the value of this is actually required and which also avoids repeated evaluations...
referencing.
See also
- JSONPJSONPJSONP or "JSON with padding" is a complement to the base JavaScript Object Notation JSON data format, a pattern of usage allowing a page to request data from a server in a different domain...
– JSON with Padding, a pattern of usage commonly employed when retrieving JSON from a webpage - BSONBSONBSON is a computer data interchange format used mainly as a data storage and network transfer format in the MongoDB database. It is a binary form for representing simple data structures and associative arrays...
– binary JSON - GeoJSONGeoJSONGeoJSON is an open format for encoding a variety of geographic data structures.It is so named because it is based on JSON...
- JSON-RPCJSON-RPCJSON-RPC is a remote procedure call protocol encoded in JSON. It is a very simple protocol , defining only a handful of data types and commands...
- SOAPjrSOAPjrSOAPjr is a protocol specification for exchanging structured information in the implementation of Web services in computer networks. It is a hybrid of SOAP and JSON-RPC .-Introduction:...
– a hybrid of SOAP and JR (JSON-RPC) - JsonMLJsonMLJsonML, the JSON Markup Language is a lightweight markup language used to map between XML and JSON...
- Comparison of data serialization formatsComparison of data serialization formatsThis is a comparison of data serialization formats, different ways to convert complex objects to sequences of bits. It does not include markup languages used exclusively as document file formats.-Overview:*a. The current default format is binary....
External links
- Format home page
- RFC 4627 - The application/json Media Type for JavaScript Object Notation (JSON)
- JSON-Introduction By Microsoft
- JSON Schema Proposal
- Limitations of JSON
- Improvements to JSON