src/cm/media/js/lib/yui/yui_3.10.3/docs/json/index.html
author Yves-Marie Haussonne <ymh.work+github@gmail.com>
Fri, 09 May 2014 18:35:26 +0200
changeset 656 a84519031134
parent 525 89ef5ed3c48b
permissions -rw-r--r--
add link to "privacy policy" in the header test

<!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">&lt;script src=&quot;http:&#x2F;&#x2F;yui.yahooapis.com&#x2F;3.10.3&#x2F;build&#x2F;yui&#x2F;yui-min.js&quot;&gt;&lt;&#x2F;script&gt;</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">&lt;script&gt;
&#x2F;&#x2F; Create a new YUI instance and populate it with the required modules.
YUI().use(&#x27;json-parse&#x27;, &#x27;json-stringify&#x27;, function (Y) {
    &#x2F;&#x2F; JSON is available and ready for use. Add implementation
    &#x2F;&#x2F; code here.
});
&lt;&#x2F;script&gt;</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(&#x27;json-parse&#x27;, function (Y) {

var jsonString = &#x27;{&quot;products&quot;:[&#x27;+
    &#x27;{&quot;id&quot;:1,&quot;price&quot;:0.99,&quot;inStock&quot;:true,&quot;name&quot;:&quot;grapes&quot;},&#x27;+
    &#x27;{&quot;id&quot;:2,&quot;price&quot;:3.5,&quot;inStock&quot;:false,&quot;name&quot;:&quot;passion fruit&quot;},&#x27;+
    &#x27;{&quot;id&quot;:3,&quot;price&quot;:2.5,&quot;inStock&quot;:true,&quot;name&quot;:&quot;bananas&quot;}&#x27;+
&#x27;]}&#x27;;

&#x2F;&#x2F; JSON.parse throws a SyntaxError when passed invalid JSON
try {
    var data = Y.JSON.parse(jsonString);
}
catch (e) {
    alert(&quot;Invalid product data&quot;);
}

&#x2F;&#x2F; We can now interact with the data
for (var i = data.products.length - 1; i &gt;= 0; --i) {
    var p = data.products[i];
    if (p.price &lt; 1) {
        p.price += 1; &#x2F;&#x2F; Price increase!
    }
}

});</pre>


<h4 id="reviver">Using the &quot;reviver&quot; 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(&#x27;json-parse&#x27;, function (Y) {

    var jsonString = &#x27;{&quot;products&quot;:[&#x27;+
        &#x27;{&quot;id&quot;:1,&quot;price&quot;:0.99,&quot;inStock&quot;:true,&quot;name&quot;:&quot;grapes&quot;},&#x27;+
        &#x27;{&quot;id&quot;:2,&quot;price&quot;:3.5,&quot;inStock&quot;:false,&quot;name&quot;:&quot;passion fruit&quot;},&#x27;+
        &#x27;{&quot;id&quot;:3,&quot;price&quot;:2.5,&quot;inStock&quot;:true,&quot;name&quot;:&quot;bananas&quot;}&#x27;+
    &#x27;]}&#x27;;

    &#x2F;&#x2F; Remove all out of stock entries and bananas.  Format prices.
    var currencySymbol = &#x27;$&#x27;;
    var reviver = function (key,val) {
        if (key === &#x27;inStock&#x27; &amp;&amp; !val) {
            return undefined;
        } else if (val === &#x27;bananas&#x27;) {
            return undefined;
        } else if (key === &#x27;price&#x27;) {
            val += val % 1 ? &quot;0&quot; : &quot;.00&quot;;
            var pIdx = val.indexOf(&#x27;.&#x27;);
            val = pIdx ? &quot;0&quot; + val : val;
            val = currencySymbol + val.substr(0,pIdx + 3);
        }

        return val;
    };

    &#x2F;&#x2F; JSON.parse throws a SyntaxError when passed invalid JSON
    try {
        var data = Y.JSON.parse(jsonString,reviver);
    }
    catch (e) {
        alert(&quot;Invalid product data&quot;);
    }

    &#x2F;&#x2F; We can now interact with the data
    alert(data.products.length); &#x2F;&#x2F; 1
    alert(data.products[0].price); &#x2F;&#x2F; $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>&lt;script&gt;</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">&#x2F;&#x2F; UNSAFE
var data = eval(&#x27;(&#x27; + shouldBeJsonData + &#x27;)&#x27;);

&#x2F;&#x2F; 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(&quot;json-stringify&quot;, function (Y) {

    var myData = {
        troop : [
            { name: &quot;Ashley&quot;, age: 12 },
            { name: &quot;Abby&quot;, age:9 }
        ]
    }; 

    var jsonStr = Y.JSON.stringify(myData);

    alert(jsonStr); &#x2F;&#x2F; {&quot;troop&quot;:[{&quot;name&quot;:&quot;Ashley&quot;,&quot;age&quot;:12},{&quot;name&quot;:&quot;Abby&quot;,&quot;age&quot;: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(&quot;json-stringify&quot;, function (Y) {

    &#x2F;&#x2F; a detailed object record set
    var records = [
        {id:1, name: &quot;Bob&quot;,   age: 47, favorite_color: &quot;blue&quot;},
        {id:2, name: &quot;Sally&quot;, age: 30, favorite_color: &quot;mauve&quot;},
        {id:3, name: &quot;Tommy&quot;, age: 13, favorite_color: &quot;black&quot;},
        {id:4, name: &quot;Chaz&quot;,  age: 26, favorite_color: &quot;plaid&quot;}
    ];

    &#x2F;&#x2F; Use an array of acceptable object key names as a whitelist.
    &#x2F;&#x2F; To create a JSON string with only age and id
    var jsonStr = Y.JSON.stringify(records,[&quot;id&quot;,&quot;age&quot;]);

    alert(jsonStr);
    &#x2F;&#x2F; [{&quot;id&quot;:1,&quot;age&quot;:47},{&quot;id&quot;:2,&quot;age&quot;:30},{&quot;id&quot;:3,&quot;age&quot;:13},{&quot;id&quot;:4,&quot;age&quot;:26}]

});</pre>


<h4 id="replacer">Using a custom &quot;replacer&quot; 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(&quot;json-stringify&quot;, function (Y) {

    &#x2F;&#x2F; a detailed object record set
    var records = [
        {id:1, name: &quot;Bob&quot;,   birthdate: &quot;2&#x2F;27&#x2F;1964&quot;, favorite_color: &quot;blue&quot;},
        {id:2, name: &quot;Sally&quot;, birthdate: &quot;9&#x2F;30&#x2F;1983&quot;, favorite_color: &quot;mauve&quot;},
        {id:3, name: &quot;Tommy&quot;, birthdate: &quot;3&#x2F;11&#x2F;1990&quot;, favorite_color: &quot;black&quot;},
        {id:4, name: &quot;Chaz&quot;,  birthdate: &quot;5&#x2F;22&#x2F;1975&quot;, favorite_color: &quot;plaid&quot;}
    ];

    &#x2F;&#x2F; Create a replacer to blacklist the id and convert the birthdate to a Date
    var replacer = function (key,val) {
        &#x2F;&#x2F; blacklist id and favorite_color
        if (key === &#x27;id&#x27; || key === &#x27;favorite_color&#x27;) {
            return undefined;

        &#x2F;&#x2F; convert birthdate to a Date instance (serialized as UTC date string)
        } else if (key === &#x27;birthdate&#x27;) {
            var d = new Date(),
                bd = val.split(&#x27;&#x2F;&#x27;);
            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);
    &#x2F;&#x2F; [{&quot;name&quot;:&quot;Bobby&quot;,&quot;birthdate&quot;:&quot;1964-02-28T08:00:00Z&quot;},{&quot;name&quot;:&quot;Sally&quot;,&quot;birthdate&quot;:&quot;1983-09-30T07:00:00Z&quot;},{&quot;name&quot;:&quot;Tommy&quot;,&quot;birthdate&quot;:&quot;1990-03-11T08:00:00Z&quot;},{&quot;name&quot;:&quot;Chaz&quot;,&quot;birthdate&quot;:&quot;1975-05-23T07:00:00Z&quot;}]

});</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(&#x27;json-stringify&#x27;, function (Y) {

    var fam = {
        family: &quot;Franklin&quot;,
        children: [ &quot;Bob&quot;, &quot;Emily&quot;, &quot;Sam&quot; ]
    };

    &#x2F;&#x2F; format serialization with four spaces
    var jsonStr = Y.JSON.stringify(fam,null,4);

    alert(jsonStr);
    &#x2F;*
    {
        &quot;family&quot;: &quot;Franklin&quot;,
        &quot;children&quot;: [
            &quot;Bob&quot;,
            &quot;Emily&quot;,
            &quot;Sam&quot;
        ]
    }
    *&#x2F;

});</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 {
    &#x2F;&#x2F; BOOM
    Y.JSON.parse(&quot;{&#x27;this string&#x27;: is, not_valid: [&#x27;J&#x27;,&#x27;S&#x27;,&#x27;O&#x27;,&#x27;N&#x27;] }&quot;);
}
catch (e) {
    alert(&quot;A string may eval to the same object, but might not be valid JSON&quot;);
}

&#x2F;&#x2F; This is safe to stringify
var myData = {
    troop : [
        { name: &quot;Ashley&quot;, age: 12 },
        { name: &quot;Abby&quot;, age:9 }
    ]
}; 

&#x2F;&#x2F; Create a cyclical reference
myData.troop[0][&quot;NEWKEY&quot;] = myData;

try {
    &#x2F;&#x2F; BOOM
    jsonStr = Y.JSON.stringify(myData);
} catch (e) {
    alert(&quot;Cyclical references can sneak in.  Remember to wrap stringify.&quot;);
}</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({
    &#x2F;&#x2F; Always use the JavaScript implementation for parsing
    useNativeJSONParse: false,

    &#x2F;&#x2F; Always use the JavaScript implementation for stringifying
    useNativeJSONStringify: false
}).use(&#x27;json&#x27;, function (Y) {
    &#x2F;&#x2F;...
});</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(&#x27;json-parse-shim&#x27;)</code> or <code>Y.use(&#x27;json-stringify-shim&#x27;)</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([{
    &quot;str&quot; : &quot;string&quot;, 
    &quot;arr&quot; : [5, &#x2F;some regex&#x2F;]
}]);
&#x2F;&#x2F;modern browsers return
[{&quot;str&quot;:&quot;string&quot;,&quot;arr&quot;:[5,{}]}]
&#x2F;&#x2F;Android 2.3.4 returns
[{&quot;str&quot;:&quot;string&quot;,&quot;arr&quot;:[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 &quot;reviver&quot; 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 &quot;replacer&quot; 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 &amp; 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>