Visit Mozilla.org

JSON

From MDC

JSON (JavaScript Object Notation) is a data-interchange format, based on a subset of JavaScript syntax. See http://json.org/ for details. JSON is useful when writting any kind of JavaScript based application, including extensions.

JSON support is anticipated in one of future versions of JavaScript (bug 340987).

One great use of JSON is to easily store objects in preferences as char preferences.

Note: The rest of this article is tailored towards extension and XUL application developers.

Contents

[edit] JSON in Firefox 2

No JSON support is included in Firefox 2. Using the code from json.org can be problematic and raise variations on bug 397595. You should adapt the code from json.org or from JSON.jsm, which provides a JSON object which can be used to serialize to JSON and parse JSON.

Note: Components.utils.import can't be used to import JSON.jsm in Firefox 2.

[edit] JSON in Firefox 3

JSON.jsm is slated to be part of Firefox 3.

[edit] Using JSON

[edit] Quick Warning

When writing privileged code, such as extensions, be careful to not just eval JSON strings (any strings, actually) from untrusted source. Either use JSON.fromString() (best), Components.utils.evalInSandbox, or parseJSON from json.org.

[edit] Tutorial on JSON.jsm

JSON can serialize objects for easy storage. Serializing is taking a JavaScript object and making it a JSON string, the JSON.toString() function is responsible for this. Parsing is taking a JSON string and returning a JavaScript object,

To serialize a javascript object:

var foo = new Object();
foo.bar = "new property";
foo.baz = 3;
var JSONfoo = JSON.toString(foo);

The JSONfoo now holds {"bar":"new property","baz":3}.

To make JSONfoo back into a JavaScript object just do:

var backToJS = JSON.fromString(JSONfoo);

[edit] Problems

You cannot serialize an object that has memebers which are functions. For example:

foo.qwerty = function(){alert('foobar');};
foo.qwerty()
var JSONfoo = JSON.toString(foo);

will raise a TypeError on line XXX: No JSON representation for this object!