YUI 2: JSON utility

Posted by gvgvasgvsz vgzavzAvv on Monday, January 17, 2011

The JSON Utility provides methods for translating data to and from JavaScript Object Notation. JSON is a safe, efficient, and reliable data interchange format. This utility defers to native JSON methods in browsers that have support, and provides JavaScript implementations that conform to the ECMAScript 5 specification for those that don't yet.

Upgrade Notes

As of version 2.8.0, browser native JSON.parse and JSON.stringify will be used if present. The native implementations are much faster and safer than any implementation done in JavaScript.
In versions prior to 2.8, the signature and behavior of YAHOO.lang.JSON.stringify differed slightly from the reference implementation at JSON.org and the ECMAScript version 5 specification that grew from that. In order to leverage native methods as browsers adopt the ECMAScript 5 spec, the YUI implementation of stringify had to change so the behavior would be consistent across browsers with and without native JSON support.
Specifically, the stringify behavior that has changed from 2.7.0 to 2.8.0 is:
  • Cyclical object references are no longer replaced with null, but now throw an Error. It is therefore recommended to wrap both parse and stringify calls in try/catch blocks.
  • The third parameter no longer limits the depth of object serialization, but is now used to trigger formatted output.
  • Objects with a toJSON method will be first transformed using this method.
  • Object keys are no longer sorted alphabetically. This is possible to do with a replacer function.
  • Overriding YAHOO.lang.JSON.dateToString is no longer recommended because the default ISO 8601 serialization is defined in the spec. If Dates must be formatted differently, either preprocess the data or set useNativeStringify to false after overriding dateToString.
The implementation of YAHOO.lang.JSON.parse has not changed in a few versions and remains a safe approximation of the spec. If your application requires specific functionality from 2.7.0 or prior, you can continue to use prior versions. They should correctly parse and produce valid JSON.

Getting Started

To use the JSON Utility, include the following source files in your web page with the script tag:

  1. <script src="http://yui.yahooapis.com/2.8.2r1/build/yahoo/yahoo-min.js"></script>


  3. <script src="http://yui.yahooapis.com/2.8.2r1/build/json/json-min.js"></script>


<script src="http://yui.yahooapis.com/2.8.2r1/build/yahoo/yahoo-min.js"></script>

<script src="http://yui.yahooapis.com/2.8.2r1/build/json/json-min.js"></script>
YUI dependency configurator.

YUI Dependency Configurator:

Instead of copying and pasting the filepaths above, try letting the YUI dependency Configurator determine the optimal file list for your desired components; the Configurator uses YUI Loader to write out the full HTML for including the precise files you need for your implementation.
Note: If you wish to include this component via the YUI Loader, its module name is json. (Click here for the full list of module names for YUI Loader.)
Where these files come from: The files included using the text above will be served from Yahoo! servers; see "Serving YUI Files from Yahoo!" for important information about this service. JavaScript files are minified, meaning that comments and white space have been removed to make them more efficient to download. To use the full, commented versions or the -debug versions of YUI JavaScript files, please download the library distribution and host the files on your own server.
Order matters: As is the case generally with JavaScript and CSS, order matters; these files should be included in the order specified above. If you include files in the wrong order, errors may result.
YAHOO.lang.JSON is a static class that does not require instantiation. Simply access the methods you need from YAHOO.lang.JSON.

Using YAHOO.lang.JSON

The JSON Utility extends YAHOO.lang, providing two static methods used for transforming data to and from JSON string format. These methods are described in the following sections.

Parsing JSON string data into JavaScript data

Pass a JSON string to YAHOO.lang.JSON.parse to convert it into live data. Optionally provide a second argument to filter or format the parsed object data during deserialization.
  1. var jsonString = '{"productId":1234,"price":24.5,"inStock":true,"bananas":null}';


  3. // Parsing JSON strings can throw a SyntaxError exception, so we wrap the call

  4. // in a try catch block

  5. try {

  6. var prod = YAHOO.lang.JSON.parse(jsonString);


  8. // We can now interact with the data

  9. if (prod.price < 25) {

  10. prod.price += 10; // Price increase!

  11. }

  12. }

  13. catch (e) {

  14. alert("Invalid product data");

  15. }


var jsonString = '{"productId":1234,"price":24.5,"inStock":true,"bananas":null}';
// Parsing JSON strings can throw a SyntaxError exception, so we wrap the call
// in a try catch block
try {
var prod = YAHOO.lang.JSON.parse(jsonString);
// We can now interact with the data
if (prod.price < 25) {
prod.price += 10; // Price increase!
catch (e) {
alert("Invalid product data");
You can filter out data or format data during parse by passing a function as the second argument to parse. Values returned from the function will take the place of the original value. Return undefined to omit a key:value pair from the returned object.
  1. var currencySymbol = "$"

  2. function myFilter(key,val) {

  3. // format price as a string

  4. if (key == "price") {

  5. var f_price = currencySymbol + val.toFixed(2);

  6. }


  8. // omit keys by returning undefined

  9. if (key == "bananas") {

  10. return undefined;

  11. }

  12. }


  14. var formattedProd = YAHOO.lang.JSON.parse(jsonString, myFilter);


  16. // key "bananas" is not present in the formattedProd object

  17. if (YAHOO.lang.isUndefined(formattedProd.bananas)) {

  18. alert("We have no bananas today");

  19. }


  21. // and the price is the formatted string "$24.50"

  22. alert("Your price: " + formattedProd.price)


var currencySymbol = "$"
function myFilter(key,val) {
// format price as a string
if (key == "price") {
var f_price = currencySymbol + val.toFixed(2);
// omit keys by returning undefined
if (key == "bananas") {
return undefined;
var formattedProd = YAHOO.lang.JSON.parse(jsonString, myFilter);
// key "bananas" is not present in the formattedProd object
if (YAHOO.lang.isUndefined(formattedProd.bananas)) {
alert("We have no bananas today");
// and the price is the formatted string "$24.50"
alert("Your price: " + formattedProd.price)

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 safe. eval is capable of executing JavaScript's full notation, including calling functions and accessing cookies with all the privileges of a

More Here


{ 0 comments... read them below or add one }

Post a Comment