Example: JSON with Y.io

A natural fit for the JSON module is to work with IO to parse JSON messages received via XMLHttpRequest (XHR). In this example, we'll request JSON data from the server using the Y.io() method and parse the resulting JSON string data.

Click the Get Messages button to send the request to the server; the response will be displayed below the button.

Use Y.JSON.parse in the success handler

Pass the XHR responseText to Y.JSON.parse() and capture the return value. Note that the parse() method can throw a SyntaxError exception, so be sure to wrap the call in a try/catch block.

Y.io('../assets/json/json-connect-response.json', {
    on : {
        success : function (tx, r) {
            var parsedResponse;

            // protected against malformed JSON response
            try {
               parsedResponse = Y.JSON.parse(r.responseText);
            }
            catch (e) {
                alert("JSON Parse failed!");
                return;
            }
        }
    }
});

The parse() method returns the native JavaScript object representation of the string data returned from the Y.io() call. In this case, the data is an array of object literals in this form:

[
    { "animal" : "Cat",  "message" : "Meow"  },
    { "animal" : "Dog",  "message" : "Woof"  },
    { "animal" : "Cow",  "message" : "Moo"   },
    { "animal" : "Duck", "message" : "Quack" },
    { "animal" : "Lion", "message" : "Roar"  }
]

In the success handler we'll simply loop through this array and outputting its contents to the DOM.

Complete Example Source

<div id="demo" class="yui3-skin-sam">
    <p>Click the <em>Get Messages</em> button to send the request to the server; the response will be displayed below the button.</p>
    <p><button>Get Messages</button></p>
    <div id="demo-messages"></div>
</div>

<script>
// Create business logic in a YUI sandbox using the 'io' and 'json' modules
YUI().use("node", "io", "dump", "json-parse", function (Y) {

    // capture the node that we'll display the messages in
    var target = Y.one('#demo-messages');

    // Create the io callback/configuration
    var callback = {

        timeout : 3000,

        on : {
            success : function (x,o) {
                Y.log("RAW JSON DATA: " + o.responseText);

                var messages = [],
                    html = '', i, l;

                // Process the JSON data returned from the server
                try {
                    messages = Y.JSON.parse(o.responseText);
                }
                catch (e) {
                    alert("JSON Parse failed!");
                    return;
                }

                Y.log("PARSED DATA: " + Y.Lang.dump(messages));

                // The returned data was parsed into an array of objects.
                // Add a P element for each received message
                for (i=0, l=messages.length; i < l; ++i) {
                    html += '<p>' + messages[i].animal + ' says "' +
                                    messages[i].message + '"</p>';
                }

                // Use the Node API to apply the new innerHTML to the target
                target.setHTML(html);
            },

            failure : function (x,o) {
                alert("Async call failed!");
            }

        }
    };

    // Attach a click event listener to the button #demo_btn to send the request
    Y.one('#demo button').on('click',function (e) {
        // Make the call to the server for JSON data
        Y.io("../assets/json/json-connect-response.json", callback);
    });

});
</script>