<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JSON</title>
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans:400,700,400italic,700italic">
<link rel="stylesheet" href="../../build/cssgrids/cssgrids-min.css">
<link rel="stylesheet" href="../assets/css/main.css">
<link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
<link rel="shortcut icon" type="image/png" href="../assets/favicon.png">
<script src="../../build/yui/yui-min.js"></script>
</head>
<body>
<!--
<a href="https://github.com/yui/yui3"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub"></a>
-->
<div id="doc">
<div id="hd">
<h1><img src="http://yuilibrary.com/img/yui-logo.png"></h1>
</div>
<a href="#toc" class="jump">Jump to Table of Contents</a>
<h1>JSON</h1>
<div class="yui3-g">
<div class="yui3-u-3-4">
<div id="main">
<div class="content"><div class="intro component">
<p>
The JSON module is an implementation of the ECMA 5 specification for
transforming data to and from <a
href="http://en.wikipedia.org/wiki/JSON">JavaScript Object
Notation</a>. JSON is a safe, efficient, and reliable data interchange
format. This module provides a JavaScript implementation of the spec,
based on <a
href="https://github.com/douglascrockford/JSON-js/blob/master/json2.js">Douglas
Crockford's json2.js</a>. For browsers with native support it defers
to the native implementation.
</p>
</div>
<h2 id="getting-started">Getting Started</h2>
<p>
To include the source files for JSON and its dependencies, first load
the YUI seed file if you haven't already loaded it.
</p>
<pre class="code prettyprint"><script src="http://yui.yahooapis.com/3.10.3/build/yui/yui-min.js"></script></pre>
<p>
Next, create a new YUI instance for your application and populate it with the
modules you need by specifying them as arguments to the <code>YUI().use()</code> method.
YUI will automatically load any dependencies required by the modules you
specify.
</p>
<pre class="code prettyprint"><script>
// Create a new YUI instance and populate it with the required modules.
YUI().use('json-parse', 'json-stringify', function (Y) {
// JSON is available and ready for use. Add implementation
// code here.
});
</script></pre>
<p>
For more information on creating YUI instances and on the
<a href="http://yuilibrary.com/yui/docs/api/classes/YUI.html#method_use"><code>use()</code> method</a>, see the
documentation for the <a href="../yui/index.html">YUI Global Object</a>.
</p>
<h2 id="using">Using the JSON Utility</h2>
<h3 id="modules">JSON module overview</h3>
<p>
The JSON module adds the namespace <code>JSON</code> to your YUI instance.
Its methods are static, available from this namespace.
</p>
<p>
To minimize the code footprint when some functionality is not required,
JSON has been broken up into the following modules:
</p>
<dl>
<dt><code>json-parse</code></dt>
<dd>
Adds <code>Y.JSON.parse(..)</code> method to the YUI instance. Use
this module if all you will be doing is parsing JSON strings.
</dd>
<dt><code>json-stringify</code></dt>
<dd>
Adds <code>Y.JSON.stringify(..)</code> 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.
</dd>
<dt><code>json</code></dt>
<dd>
A rollup of <code>json-parse</code> and <code>json-stringify</code>
modules. Use this if you need to both parse JSON strings and serialize
objects to JSON strings.
</dd>
</dl>
<h3 id="parse">Parsing JSON strings into native JavaScript values</h3>
<p>
Provided a string containing data in JSON format, simply pass the string to
<code>parse</code> and capture the return value.
</p>
<pre class="code prettyprint">YUI().use('json-parse', function (Y) {
var jsonString = '{"products":['+
'{"id":1,"price":0.99,"inStock":true,"name":"grapes"},'+
'{"id":2,"price":3.5,"inStock":false,"name":"passion fruit"},'+
'{"id":3,"price":2.5,"inStock":true,"name":"bananas"}'+
']}';
// JSON.parse throws a SyntaxError when passed invalid JSON
try {
var data = Y.JSON.parse(jsonString);
}
catch (e) {
alert("Invalid product data");
}
// We can now interact with the data
for (var i = data.products.length - 1; i >= 0; --i) {
var p = data.products[i];
if (p.price < 1) {
p.price += 1; // Price increase!
}
}
});</pre>
<h4 id="reviver">Using the "reviver" parameter</h4>
<p>
The optional second parameter to <code>parse</code> 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 <code>undefined</code>, the key will be omitted
from the returned object.
</p>
<p>
Typical uses of reviver functions are filtering, formatting, and value
conversion.
</p>
<pre class="code prettyprint">YUI().use('json-parse', function (Y) {
var jsonString = '{"products":['+
'{"id":1,"price":0.99,"inStock":true,"name":"grapes"},'+
'{"id":2,"price":3.5,"inStock":false,"name":"passion fruit"},'+
'{"id":3,"price":2.5,"inStock":true,"name":"bananas"}'+
']}';
// Remove all out of stock entries and bananas. Format prices.
var currencySymbol = '$';
var reviver = function (key,val) {
if (key === 'inStock' && !val) {
return undefined;
} else if (val === 'bananas') {
return undefined;
} else if (key === 'price') {
val += val % 1 ? "0" : ".00";
var pIdx = val.indexOf('.');
val = pIdx ? "0" + val : val;
val = currencySymbol + val.substr(0,pIdx + 3);
}
return val;
};
// JSON.parse throws a SyntaxError when passed invalid JSON
try {
var data = Y.JSON.parse(jsonString,reviver);
}
catch (e) {
alert("Invalid product data");
}
// We can now interact with the data
alert(data.products.length); // 1
alert(data.products[0].price); // $0.99
});</pre>
<h4 id="avoid_eval">A word of caution against using <code>eval</code></h4>
<p>
JSON data format is a <em>subset</em> of JavaScript notation, meaning that
it is possible to use JavaScript <code>eval</code> to transform JSON data
to live data. However, it is unsafe practice to assume that data reaching
your code is not malicious. <code>eval</code> is capable of executing
JavaScript's full syntax, including calling functions and accessing cookies
with all the privileges of a <code><script></code>. To ensure that
the data is safe, the JSON module's <code>parse</code> method inspects the
incoming string (using methods derived from Douglas Crockford's <a
href="https://github.com/douglascrockford/JSON-js/blob/master/json2.js">json2.js</a>)
and verifies that it is safe before giving it the green light to parse.
</p>
<pre class="code prettyprint">// UNSAFE
var data = eval('(' + shouldBeJsonData + ')');
// Safe
var data = Y.JSON.parse(shouldBeJsonData);</pre>
<h3 id="stringify">Creating JSON strings from JavaScript objects</h3>
<p>
To convert a JavaScript object (or any permissable value) to a JSON string,
pass that object to <code>Y.JSON.stringify</code> and capture the returned
string.
</p>
<pre class="code prettyprint">YUI().use("json-stringify", function (Y) {
var myData = {
troop : [
{ name: "Ashley", age: 12 },
{ name: "Abby", age:9 }
]
};
var jsonStr = Y.JSON.stringify(myData);
alert(jsonStr); // {"troop":[{"name":"Ashley","age":12},{"name":"Abby","age":9}]}
});</pre>
<h4 id="whitelist">Using a whitelist</h4>
<p>
To serialize only a fixed subset of keys, provide an array of key names as
the second parameter to <code>stringify</code>.
</p>
<pre class="code prettyprint">YUI().use("json-stringify", function (Y) {
// a detailed object record set
var records = [
{id:1, name: "Bob", age: 47, favorite_color: "blue"},
{id:2, name: "Sally", age: 30, favorite_color: "mauve"},
{id:3, name: "Tommy", age: 13, favorite_color: "black"},
{id:4, name: "Chaz", age: 26, favorite_color: "plaid"}
];
// Use an array of acceptable object key names as a whitelist.
// To create a JSON string with only age and id
var jsonStr = Y.JSON.stringify(records,["id","age"]);
alert(jsonStr);
// [{"id":1,"age":47},{"id":2,"age":30},{"id":3,"age":13},{"id":4,"age":26}]
});</pre>
<h4 id="replacer">Using a custom "replacer" function</h4>
<p>
For more granular control of how values in your object are serialized, you
can pass a replacer function as the second parameter to
<code>stringify</code>. 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.
</p>
<pre class="code prettyprint">YUI().use("json-stringify", function (Y) {
// a detailed object record set
var records = [
{id:1, name: "Bob", birthdate: "2/27/1964", favorite_color: "blue"},
{id:2, name: "Sally", birthdate: "9/30/1983", favorite_color: "mauve"},
{id:3, name: "Tommy", birthdate: "3/11/1990", favorite_color: "black"},
{id:4, name: "Chaz", birthdate: "5/22/1975", favorite_color: "plaid"}
];
// Create a replacer to blacklist the id and convert the birthdate to a Date
var replacer = function (key,val) {
// blacklist id and favorite_color
if (key === 'id' || key === 'favorite_color') {
return undefined;
// convert birthdate to a Date instance (serialized as UTC date string)
} else if (key === 'birthdate') {
var d = new Date(),
bd = val.split('/');
d.setFullYear(bd[2],bd[0]-1,bd[1]);
d.setHours(0,0,0);
return d;
}
return val;
};
var jsonStr = Y.JSON.stringify(records,replacer);
alert(jsonStr);
// [{"name":"Bobby","birthdate":"1964-02-28T08:00:00Z"},{"name":"Sally","birthdate":"1983-09-30T07:00:00Z"},{"name":"Tommy","birthdate":"1990-03-11T08:00:00Z"},{"name":"Chaz","birthdate":"1975-05-23T07:00:00Z"}]
});</pre>
<h4 id="format">Formatting JSON output</h4>
<p>
To create readable JSON, pass a string or number as the third parameter to
<code>stringify</code>. 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.
</p>
<pre class="code prettyprint">YUI().use('json-stringify', function (Y) {
var fam = {
family: "Franklin",
children: [ "Bob", "Emily", "Sam" ]
};
// format serialization with four spaces
var jsonStr = Y.JSON.stringify(fam,null,4);
alert(jsonStr);
/*
{
"family": "Franklin",
"children": [
"Bob",
"Emily",
"Sam"
]
}
*/
});</pre>
<h3 id="errors">Catching JSON errors</h3>
<p>
ECMA 5 states that <code>parse</code> should throw an error when an invalid
JSON string is input. It also states that <code>stringify</code> should
throw an error when an object with cyclical references is input.
</p>
<p>
For this reason, it is recommended that both <code>parse</code> and
<code>stringify</code> be called from within
<code>try</code>/<code>catch</code> blocks.
</p>
<pre class="code prettyprint">try {
// BOOM
Y.JSON.parse("{'this string': is, not_valid: ['J','S','O','N'] }");
}
catch (e) {
alert("A string may eval to the same object, but might not be valid JSON");
}
// This is safe to stringify
var myData = {
troop : [
{ name: "Ashley", age: 12 },
{ name: "Abby", age:9 }
]
};
// Create a cyclical reference
myData.troop[0]["NEWKEY"] = myData;
try {
// BOOM
jsonStr = Y.JSON.stringify(myData);
} catch (e) {
alert("Cyclical references can sneak in. Remember to wrap stringify.");
}</pre>
<h3 id="native">Notes about native JSON support</h3>
<p>
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 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 certain browsers.
</p>
<p>
In general, it is preferable to use the native behavior for
<code>JSON.parse</code> as it is much faster and safer than any JavaScript
implementation. There are also very few known critical issues with
supporting browsers.
</p>
<p>
Stringify has more pitfalls and inconsistencies, but they may not affect
your use cases. As with <code>parse</code>, the native implementation of
<code>stringify</code> 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.
</p>
<p>
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 <code>parse</code> or <code>stringify</code> by setting
the <code>useNativeJSONParse</code> and
<code>useNativeJSONStringify</code> configuration options.
</p>
<pre class="code prettyprint">YUI({
// Always use the JavaScript implementation for parsing
useNativeJSONParse: false,
// Always use the JavaScript implementation for stringifying
useNativeJSONStringify: false
}).use('json', function (Y) {
//...
});</pre>
<h4 id="changes-in-390">Changes in 3.9.0</h4>
<p>
As of version 3.9.0 YUI has changed to loading the JavaScript
implementation of JSON only when the browser does not provide a native
API. You can no longer change the desired implementation at run-time
by changing <code>Y.JSON.useNativeParse</code>. Since native JSON implementations
have become much more stable this results in a smaller download
for most users. You can still chose to use the JavaScript fallback
by calling <code>Y.use('json-parse-shim')</code> or <code>Y.use('json-stringify-shim')</code>.
</p>
<h2 id="issues">Known Issues</h2>
<ul class="spaced">
<li>
<p>Native JSON.stringify treats regex values as a function on Android 2.3.</p>
<pre class="code prettyprint">Y.JSON.stringify([{
"str" : "string",
"arr" : [5, /some regex/]
}]);
//modern browsers return
[{"str":"string","arr":[5,{}]}]
//Android 2.3.4 returns
[{"str":"string","arr":[5,null]}]</pre>
</li>
</ul>
</div>
</div>
</div>
<div class="yui3-u-1-4">
<div class="sidebar">
<div id="toc" class="sidebox">
<div class="hd">
<h2 class="no-toc">Table of Contents</h2>
</div>
<div class="bd">
<ul class="toc">
<li>
<a href="#getting-started">Getting Started</a>
</li>
<li>
<a href="#using">Using the JSON Utility</a>
<ul class="toc">
<li>
<a href="#modules">JSON module overview</a>
</li>
<li>
<a href="#parse">Parsing JSON strings into native JavaScript values</a>
<ul class="toc">
<li>
<a href="#reviver">Using the "reviver" parameter</a>
</li>
<li>
<a href="#avoid_eval">A word of caution against using <code>eval</code></a>
</li>
</ul>
</li>
<li>
<a href="#stringify">Creating JSON strings from JavaScript objects</a>
<ul class="toc">
<li>
<a href="#whitelist">Using a whitelist</a>
</li>
<li>
<a href="#replacer">Using a custom "replacer" function</a>
</li>
<li>
<a href="#format">Formatting JSON output</a>
</li>
</ul>
</li>
<li>
<a href="#errors">Catching JSON errors</a>
</li>
<li>
<a href="#native">Notes about native JSON support</a>
<ul class="toc">
<li>
<a href="#changes-in-390">Changes in 3.9.0</a>
</li>
</ul>
</li>
</ul>
</li>
<li>
<a href="#issues">Known Issues</a>
</li>
</ul>
</div>
</div>
<div class="sidebox">
<div class="hd">
<h2 class="no-toc">Examples</h2>
</div>
<div class="bd">
<ul class="examples">
<li data-description="Use JSON to parse data received via XMLHttpRequest via Y.io calls — a simple JSON use case.">
<a href="json-connect.html">JSON with Y.io</a>
</li>
<li data-description="Use the replacer and reviver parameters to reconstitute object instances that have been serialized to JSON.">
<a href="json-freeze-thaw.html">Rebuilding Class Instances from JSON Data</a>
</li>
<li data-description="Use a currency conversion calculation to add a new price member to a JSON response, demonstrating how JSON data, once retrieved, can be transformed during parsing.">
<a href="json-convert-values.html">Adding New Object Members During Parsing</a>
</li>
</ul>
</div>
</div>
<div class="sidebox">
<div class="hd">
<h2 class="no-toc">Examples That Use This Component</h2>
</div>
<div class="bd">
<ul class="examples">
<li data-description="A basic todo list built with the Model, Model List, and View components.">
<a href="../app/app-todo.html">Todo List</a>
</li>
<li data-description="Portal style example using Drag & Drop Event Bubbling and Animation.">
<a href="../dd/portal-drag.html">Portal Style Example</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="../assets/vendor/prettify/prettify-min.js"></script>
<script>prettyPrint();</script>
<script>
YUI.Env.Tests = {
examples: [],
project: '../assets',
assets: '../assets/json',
name: 'json',
title: 'JSON',
newWindow: '',
auto: false
};
YUI.Env.Tests.examples.push('json-connect');
YUI.Env.Tests.examples.push('json-freeze-thaw');
YUI.Env.Tests.examples.push('json-convert-values');
YUI.Env.Tests.examples.push('app-todo');
YUI.Env.Tests.examples.push('portal-drag');
</script>
<script src="../assets/yui/test-runner.js"></script>
</body>
</html>