6
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Maven+Pro:400,700">
7
<link rel="stylesheet" href="../../build/cssgrids/grids-min.css">
8
<link rel="stylesheet" href="../assets/css/main.css">
9
<link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
10
<script src="../../build/yui/yui-min.js"></script>
18
<a href="#toc" class="jump">Jump to Table of Contents</a>
22
<div class="yui3-u-3-4">
24
<div class="content"><div class="intro component">
26
The JSON module is an implementation of the ECMA 5 specification for
27
transforming data to and from <a
28
href="http://en.wikipedia.org/wiki/JSON">JavaScript Object
29
Notation</a>. JSON is a safe, efficient, and reliable data interchange
30
format. This module provides a JavaScript implementation of the spec,
32
href="https://github.com/douglascrockford/JSON-js/blob/master/json2.js">Douglas
33
Crockford's json2.js</a>. For browsers with native support it defers
34
to the native implementation.
38
<h2 id="getting-started">Getting Started</h2>
41
To include the source files for JSON and its dependencies, first load
42
the YUI seed file if you haven't already loaded it.
45
<pre class="code prettyprint"><script src="http://yui.yahooapis.com/3.5.0/build/yui/yui-min.js"></script></pre>
49
Next, create a new YUI instance for your application and populate it with the
50
modules you need by specifying them as arguments to the <code>YUI().use()</code> method.
51
YUI will automatically load any dependencies required by the modules you
55
<pre class="code prettyprint"><script>
56
// Create a new YUI instance and populate it with the required modules.
57
YUI().use('json-parse', 'json-stringify', function (Y) {
58
// JSON is available and ready for use. Add implementation
59
// code here.
61
</script></pre>
65
For more information on creating YUI instances and on the
66
<a href="http://yuilibrary.com/yui/docs/api/classes/YUI.html#method_use"><code>use()</code> method</a>, see the
67
documentation for the <a href="../yui/index.html">YUI Global Object</a>.
71
<h2 id="using">Using the JSON Utility</h2>
73
<h3 id="modules">JSON module overview</h3>
76
The JSON module adds the namespace <code>JSON</code> to your YUI instance.
77
Its methods are static, available from this namespace.
81
To minimize the code footprint when some functionality is not required,
82
JSON has been broken up into the following modules:
86
<dt><code>json-parse</code></dt>
88
Adds <code>Y.JSON.parse(..)</code> method to the YUI instance. Use
89
this module if all you will be doing is parsing JSON strings.
92
<dt><code>json-stringify</code></dt>
94
Adds <code>Y.JSON.stringify(..)</code> method and its supporting
95
methods and properties to the YUI instance. Use this module if all you
96
will be doing is serializing JavaScript objects to JSON strings.
99
<dt><code>json</code></dt>
101
A rollup of <code>json-parse</code> and <code>json-stringify</code>
102
modules. Use this if you need to both parse JSON strings and serialize
103
objects to JSON strings.
107
<h3 id="parse">Parsing JSON strings into native JavaScript values</h3>
110
Provided a string containing data in JSON format, simply pass the string to
111
<code>parse</code> and capture the return value.
114
<pre class="code prettyprint">YUI().use('json-parse', function (Y) {
116
var jsonString = '{"products":['+
117
'{"id":1,"price":0.99,"inStock":true,"name":"grapes"},'+
118
'{"id":2,"price":3.5,"inStock":false,"name":"passion fruit"},'+
119
'{"id":3,"price":2.5,"inStock":true,"name":"bananas"}'+
122
// JSON.parse throws a SyntaxError when passed invalid JSON
124
var data = Y.JSON.parse(jsonString);
127
alert("Invalid product data");
130
// We can now interact with the data
131
for (var i = data.products.length - 1; i >= 0; --i) {
132
var p = data.products[i];
133
if (p.price < 1) {
134
p.price += 1; // Price increase!
141
<h4 id="reviver">Using the "reviver" parameter</h4>
144
The optional second parameter to <code>parse</code> accepts a function that
145
will be executed on each member of the parsed JavaScript object. Each call
146
to the reviver function is passed the key and associated value, and is
147
executed from the context of the object containing the key. If the return
148
value of the reviver is <code>undefined</code>, the key will be omitted
149
from the returned object.
153
Typical uses of reviver functions are filtering, formatting, and value
158
<pre class="code prettyprint">YUI().use('json-parse', function (Y) {
160
var jsonString = '{"products":['+
161
'{"id":1,"price":0.99,"inStock":true,"name":"grapes"},'+
162
'{"id":2,"price":3.5,"inStock":false,"name":"passion fruit"},'+
163
'{"id":3,"price":2.5,"inStock":true,"name":"bananas"}'+
166
// Remove all out of stock entries and bananas. Format prices.
167
var currencySymbol = '$';
168
var reviver = function (key,val) {
169
if (key === 'inStock' && !val) {
171
} else if (val === 'bananas') {
173
} else if (key === 'price') {
174
val += val % 1 ? "0" : ".00";
175
var pIdx = val.indexOf('.');
176
val = pIdx ? "0" + val : val;
177
val = currencySymbol + val.substr(0,pIdx + 3);
183
// JSON.parse throws a SyntaxError when passed invalid JSON
185
var data = Y.JSON.parse(jsonString,reviver);
188
alert("Invalid product data");
191
// We can now interact with the data
192
alert(data.products.length); // 1
193
alert(data.products[0].price); // $0.99
198
<h4 id="avoid_eval">A word of caution against using <code>eval</code></h4>
201
JSON data format is a <em>subset</em> of JavaScript notation, meaning that
202
it is possible to use JavaScript <code>eval</code> to transform JSON data
203
to live data. However, it is unsafe practice to assume that data reaching
204
your code is not malicious. <code>eval</code> is capable of executing
205
JavaScript's full syntax, including calling functions and accessing cookies
206
with all the privileges of a <code><script></code>. To ensure that
207
the data is safe, the JSON module's <code>parse</code> method inspects the
208
incoming string (using methods derived from Douglas Crockford's <a
209
href="https://github.com/douglascrockford/JSON-js/blob/master/json2.js">json2.js</a>)
210
and verifies that it is safe before giving it the green light to parse.
213
<pre class="code prettyprint">// UNSAFE
214
var data = eval('(' + shouldBeJsonData + ')');
217
var data = Y.JSON.parse(shouldBeJsonData);</pre>
220
<h3 id="stringify">Creating JSON strings from JavaScript objects</h3>
223
To convert a JavaScript object (or any permissable value) to a JSON string,
224
pass that object to <code>Y.JSON.stringify</code> and capture the returned
228
<pre class="code prettyprint">YUI().use("json-stringify", function (Y) {
232
{ name: "Ashley", age: 12 },
233
{ name: "Abby", age:9 }
237
var jsonStr = Y.JSON.stringify(myData);
239
alert(jsonStr); // {"troop":[{"name":"Ashley","age":12},{"name":"Abby","age":9}]}
243
<h4 id="whitelist">Using a whitelist</h4>
246
To serialize only a fixed subset of keys, provide an array of key names as
247
the second parameter to <code>stringify</code>.
250
<pre class="code prettyprint">YUI().use("json-stringify", function (Y) {
252
// a detailed object record set
254
{id:1, name: "Bob", age: 47, favorite_color: "blue"},
255
{id:2, name: "Sally", age: 30, favorite_color: "mauve"},
256
{id:3, name: "Tommy", age: 13, favorite_color: "black"},
257
{id:4, name: "Chaz", age: 26, favorite_color: "plaid"}
260
// Use an array of acceptable object key names as a whitelist.
261
// To create a JSON string with only age and id
262
var jsonStr = Y.JSON.stringify(records,["id","age"]);
265
// [{"id":1,"age":47},{"id":2,"age":30},{"id":3,"age":13},{"id":4,"age":26}]
270
<h4 id="replacer">Using a custom "replacer" function</h4>
273
For more granular control of how values in your object are serialized, you
274
can pass a replacer function as the second parameter to
275
<code>stringify</code>. The replacer will be called for each key value
276
pair, and executed from the context of the key's host object. The return
277
value of the replacer will be serialized in place of the raw value.
280
<pre class="code prettyprint">YUI().use("json-stringify", function (Y) {
282
// a detailed object record set
284
{id:1, name: "Bob", birthdate: "2/27/1964", favorite_color: "blue"},
285
{id:2, name: "Sally", birthdate: "9/30/1983", favorite_color: "mauve"},
286
{id:3, name: "Tommy", birthdate: "3/11/1990", favorite_color: "black"},
287
{id:4, name: "Chaz", birthdate: "5/22/1975", favorite_color: "plaid"}
290
// Create a replacer to blacklist the id and convert the birthdate to a Date
291
var replacer = function (key,val) {
292
// blacklist id and favorite_color
293
if (key === 'id' || key === 'favorite_color') {
296
// convert birthdate to a Date instance (serialized as UTC date string)
297
} else if (key === 'birthdate') {
299
bd = val.split('/');
300
d.setFullYear(bd[2],bd[0]-1,bd[1]);
308
var jsonStr = Y.JSON.stringify(records,replacer);
311
// [{"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"}]
316
<h4 id="format">Formatting JSON output</h4>
319
To create readable JSON, pass a string or number as the third parameter to
320
<code>stringify</code>. Object and Array members will be separated with
321
newlines and indented. If a string is supplied, that string will be used
322
for the indentation. If a number is passed, that number of spaces will be
326
<pre class="code prettyprint">YUI().use('json-stringify', function (Y) {
329
family: "Franklin",
330
children: [ "Bob", "Emily", "Sam" ]
333
// format serialization with four spaces
334
var jsonStr = Y.JSON.stringify(fam,null,4);
339
"family": "Franklin",
340
"children": [
351
<h3 id="errors">Catching JSON errors</h3>
354
ECMA 5 states that <code>parse</code> should throw an error when an invalid
355
JSON string is input. It also states that <code>stringify</code> should
356
throw an error when an object with cyclical references is input.
360
For this reason, it is recommended that both <code>parse</code> and
361
<code>stringify</code> be called from within
362
<code>try</code>/<code>catch</code> blocks.
365
<pre class="code prettyprint">try {
367
Y.JSON.parse("{'this string': is, not_valid: ['J','S','O','N'] }");
370
alert("A string may eval to the same object, but might not be valid JSON");
373
// This is safe to stringify
376
{ name: "Ashley", age: 12 },
377
{ name: "Abby", age:9 }
381
// Create a cyclical reference
382
myData.troop[0]["NEWKEY"] = myData;
386
jsonStr = Y.JSON.stringify(myData);
388
alert("Cyclical references can sneak in. Remember to wrap stringify.");
392
<h3 id="native">Notes about current native JSON support</h3>
395
Native JSON support in JavaScript is defined in the ECMAScript 5
396
specification, which was finalized in September 2009. However, most of the
397
major browser vendors had already implemented this feature in recent
398
versions of their JavaScript engines while the spec was still in draft. As
399
a result of the timing and the fact that native JSON is a new feature,
400
there are gotchas involved in leveraging the disparate native
405
In general, it is preferable to use the native behavior for
406
<code>JSON.parse</code> as it is much faster and safer than any JavaScript
407
implementation. There are also very few known critical issues with
413
Stringify has more pitfalls and inconsistencies, but they may not affect
414
your use cases. As with <code>parse</code>, the native implementation of
415
<code>stringify</code> is faster, but only marginally so with reasonably
416
sized input. In most cases, choosing the JavaScript implementation will
417
not affect performance and may be preferable for its cross browser
423
As noted above, the JSON module will leverage native behavior in
424
implementing browsers by default. However, you can choose to opt out of
425
leveraging native <code>parse</code> or <code>stringify</code> by setting
426
the <code>Y.JSON.useNativeParse</code> and
427
<code>Y.JSON.useNativeStringify</code> static properties.
431
<pre class="code prettyprint">YUI().use('json', function (Y) {
433
// Always use the JavaScript implementation for parsing
434
Y.JSON.useNativeParse = false;
436
// Always use the JavaScript implementation for stringifying
437
Y.JSON.useNativeStringify = false;
446
<div class="yui3-u-1-4">
447
<div class="sidebar">
449
<div id="toc" class="sidebox">
451
<h2 class="no-toc">Table of Contents</h2>
457
<a href="#getting-started">Getting Started</a>
460
<a href="#using">Using the JSON Utility</a>
463
<a href="#modules">JSON module overview</a>
466
<a href="#parse">Parsing JSON strings into native JavaScript values</a>
469
<a href="#reviver">Using the "reviver" parameter</a>
472
<a href="#avoid_eval">A word of caution against using <code>eval</code></a>
477
<a href="#stringify">Creating JSON strings from JavaScript objects</a>
480
<a href="#whitelist">Using a whitelist</a>
483
<a href="#replacer">Using a custom "replacer" function</a>
486
<a href="#format">Formatting JSON output</a>
491
<a href="#errors">Catching JSON errors</a>
494
<a href="#native">Notes about current native JSON support</a>
504
<div class="sidebox">
506
<h2 class="no-toc">Examples</h2>
510
<ul class="examples">
513
<li data-description="Use JSON to parse data received via XMLHttpRequest via Y.io calls — a simple JSON use case.">
514
<a href="json-connect.html">JSON with Y.io</a>
519
<li data-description="Use the replacer and reviver parameters to reconstitute object instances that have been serialized to JSON.">
520
<a href="json-freeze-thaw.html">Rebuilding Class Instances from JSON Data</a>
525
<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.">
526
<a href="json-convert-values.html">Adding New Object Members During Parsing</a>
540
<div class="sidebox">
542
<h2 class="no-toc">Examples That Use This Component</h2>
546
<ul class="examples">
555
<li data-description="A basic todo list built with the Model, Model List, and View components.">
556
<a href="../app/app-todo.html">Todo List</a>
561
<li data-description="Portal style example using Drag & Drop Event Bubbling and Animation.">
562
<a href="../dd/portal-drag.html">Portal Style Example</a>
575
<script src="../assets/vendor/prettify/prettify-min.js"></script>
576
<script>prettyPrint();</script>