Note: This is the YUI 3.x site. Looking for the YUI 2.x site?

YUI 3: The JSON Utility

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. The module provides a JavaScript implementation based on Douglas Crockford's json2.js for browsers without native support and defers to the native browser implementation if available.

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 the JSON

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

JSON modules overview

The JSON Utility 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 can be passed 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. Similarly, 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.

Support & Community

Forum & Blog

There is a dedicated mailing list for YUI 3. Click the link to visit the list, or use the form below to subscribe:

 

You might also be interested in the general YUI list: ydn-javascript.

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