YUI 3: JSON

The JSON module is an implementation of the ECMA 5 specification for transforming data to and from JavaScript Object Notation. JSON is a safe, efficient, and reliable data interchange format. This module provides a JavaScript implementation of the spec, based on Douglas Crockford's json2.js. For browsers with native support it defers to the native implementation.

Getting Started

Include Dependencies

The easiest way to include the source files for JSON and its dependencies is to add the YUI seed file to your page, using the following script tag, and allow the YUI instance to download any additional files which may be required:

The YUI instance will automatically pull down JSON's source files and any missing dependencies when the json module is used. This helps you avoid having to manually manage the list of files needed on your page to support multiple components while also optimizing your initial page weight by loading files only when they are required.

If you do want to include file dependencies manually on your page, the YUI Dependency Configurator can be used to determine the list of files you need to include in order to use JSON.

The YUI Instance

Once you have the YUI seed file on your page (yui-min.js), you can create a new YUI instance for your application to use and populate it with the modules you need, specified as the first set of arguments to the use method:

The last argument passed to use is a callback function. The callback function will be invoked as soon as the YUI instance is done downloading any required files missing from your page. Once those files are loaded, your local YUI instance will be supplemented with the classes which make up the json module and any modules it depends on. A reference to the populated YUI instance (Y) is passed back to your callback function. Within your callback, then, you can start writing your application code based on your own custom instance of YUI.

For more information on creating instances of YUI and the use method, see the YUI Global object documentation.

Using JSON Utility

This section describes how to use the JSON Utility module in further detail. It contains these subsections:

JSON module overview

The JSON module adds the namespace JSON to your YUI instance. Its methods are static, available from this namespace.

To minimize the code footprint when some functionality is not required, JSON has been broken up into the following modules:

json-parse
Adds Y.JSON.parse(..) method to the YUI instance. Use this module if all you will be doing is parsing JSON strings.
json-stringify
Adds Y.JSON.stringify(..) method and its supporting methods and properties to the YUI instance. Use this module if all you will be doing is serializing JavaScript objects to JSON strings.
json
A rollup of json-parse and json-stringify modules. Use this if you need to both parse JSON strings and serialize objects to JSON strings.

Parsing JSON strings into native JavaScript values

Provided a string containing data in JSON format, simply pass the string to parse and capture the return value.

Using the "reviver" parameter

The optional second parameter to parse accepts a function that will be executed on each member of the parsed JavaScript object. Each call to the reviver function is passed the key and associated value, and is executed from the context of the object containing the key. If the return value of the reviver is undefined, the key will be omitted from the returned object.

Typical uses of reviver functions are filtering, formatting, and value conversion.

A word of caution against using eval

JSON data format is a subset of JavaScript notation, meaning that it is possible to use JavaScript eval to transform JSON data to live data. However, it is unsafe practice to assume that data reaching your code is not malicious. eval is capable of executing JavaScript's full syntax, including calling functions and accessing cookies with all the privileges of a <script>. To ensure that the data is safe, the JSON module's parse method inspects the incoming string (using methods derived from Douglas Crockford's json2.js) and verifies that it is safe before giving it the green light to parse.

Creating JSON strings from JavaScript objects

To convert a JavaScript object (or any permissable value) to a JSON string, pass that object to Y.JSON.stringify and capture the returned string.

Using a whitelist

To serialize only a fixed subset of keys, provide an array of key names as the second parameter to stringify.

Using a custom "replacer" function

For more granular control of how values in your object are serialized, you can pass a replacer function as the second parameter to stringify. The replacer will be called for each key value pair, and executed from the context of the key's host object. The return value of the replacer will be serialized in place of the raw value.

Formatting JSON output

To create readable JSON, pass a string or number as the third parameter to stringify. Object and Array members will be separated with newlines and indented. If a string is supplied, that string will be used for the indentation. If a number is passed, that number of spaces will be used.

Catching JSON errors

ECMA 5 states that parse should throw an error when an invalid JSON string is input. It also states that stringify should throw an error when an object with cyclical references is input.

For this reason, it is recommended that both parse and stringify be called from within try/catch blocks.

Notes about current native JSON support

Native JSON support in JavaScript is defined in the ECMAScript 5 specification, which was finalized in September 2009. However, most of the major browser vendors had already implemented this feature in recent versions of their JavaScript engines while the spec was still in draft. As a result of the timing and the fact that native JSON is a new feature, there are gotchas involved in leveraging the disparate native behaviors.

In general, it is preferable to use the native behavior for JSON.parse as it is much faster and safer than any JavaScript implementation. There are also very few known critical issues with supporting browsers.

Stringify has more pitfalls and inconsistencies, but they may not affect your use cases. As with parse, the native implementation of stringify is faster, but only marginally so with reasonably sized input. In most cases, choosing the JavaScript implementation will not affect performance and may be preferable for its cross browser consistency.

As noted above, the JSON module will leverage native behavior in implementing browsers by default. However, you can choose to opt out of leveraging native parse or stringify by setting the Y.JSON.useNativeParse and Y.JSON.useNativeStringify static properties.

Support & Community

Forums & Blog

YUI 3 discussion forums are hosted on YUILibrary.com.

In addition, please visit the YUIBlog for updates and articles about the YUI Library written by the library's developers.

Filing Bugs & Feature Requests

The YUI Library's public bug tracking and feature request repositories are located on the YUILibrary.com site. Before filing new feature requests or bug reports, please review our reporting guidelines.

Copyright © 2009 Yahoo! Inc. All rights reserved. Copyright | Privacy Policy | Terms of Use | Job Openings