Stringify.js revision 055efb6373eaf6d68041128d6a259f50b3b02ba9
2ronwalf * Provides Y.JSON.stringify method for converting objects to JSON strings. 2ronwalf * Regex used to replace special characters in strings for JSON 2ronwalf * Character substitution map for common escapes and special characters. 2ronwalf * Serializes a Date instance as a UTC date string. Used internally by 2ronwalf * stringify. Override this method if you need Dates serialized in a 2ronwalf * @param d {Date} The Date to serialize 2ronwalf * @return {String} stringified Date in UTC format YYYY-MM-DDTHH:mm:SSZ 10daenzerorama * Converts an arbitrary value to a JSON string representation. 10daenzerorama * Cyclical object or array references are replaced with null. 10daenzerorama * If a whitelist is provided, only matching object keys will be included. 10daenzerorama * If a depth limit is provided, objects and arrays at that depth will 10daenzerorama * @param o {MIXED} any arbitrary object to convert to JSON string 10daenzerorama * @param w {Array} (optional) whitelist of acceptable object keys to include 10daenzerorama * @return {string} JSON string representation of the input rep = typeof w === 'function' ? w : null, pstack = []; // Processing stack used for cyclical ref protection if (rep || typeof w !== 'object') { // escape encode special characters var _char = function (c) { m[c] = '\\u00' + Math.floor(a / 16).toString(16) + // Enclose the escaped string in double quotes var _string = function (s) { return '"' + s.replace(str_re, _char) + '"'; // Use the configured date conversion var _date = Y.JSON.dateToString; // Worker function. Fork behavior on data type and recurse objects and // arrays per the configured depth. var _stringify = function (h,key,d) { var o = typeof rep === 'function' ? rep.call(h,key,h[key]) : h[key], i,len,j, // array iteration a; // composition array for performance over string concat // native boolean and Boolean instance if (t === 'boolean' || o instanceof Boolean) { // native number and Number instance if (t === 'number' || o instanceof Number) { return isFinite(o) ? String(o) : 'null'; // Check for cyclical references for (i = pstack.length - 1; i >= 0; --i) { // Add the object to the processing stack pstack[pstack.length] = o; // Only recurse if we're above depth config for (i = o.length - 1; i >= 0; --i) { a[i] = _stringify(o,i,d-1) || 'null'; // If whitelist provided, take only those keys k = isA(w) ? w : Y.Object.keys(w||o); for (i = 0, j = 0, len = k.length; i < len; ++i) { if (typeof k[i] === 'string') { v = _stringify(o,k[i],d-1); a[j++] = _string(k[i]) + ':' + v; // remove the array from the stack return isA(o) ? '['+a.join(',')+']' : '{'+a.join(',')+'}'; return undefined; // invalid input // Default depth to POSITIVE_INFINITY return _stringify({'':o},'',d);