2 Copyright (c) 2009, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.net/yui/license.txt
8 YUI.add('json-stringify', function(Y) {
11 * Provides Y.JSON.stringify method for converting objects to JSON strings.
14 * @submodule json-stringify
18 var _JSON = Y.config.win.JSON,
20 isFunction= Lang.isFunction,
21 isObject = Lang.isObject,
22 isArray = Lang.isArray,
23 _toStr = Object.prototype.toString,
24 Native = (_toStr.call(_JSON) === '[object JSON]' && _JSON),
25 UNDEFINED = 'undefined',
33 'undefined' : UNDEFINED,
35 '[object String]' : STRING,
37 '[object Number]' : NUMBER,
39 '[object Boolean]' : BOOLEAN,
40 '[object Date]' : DATE,
41 '[object RegExp]' : OBJECT
54 // Regex used to capture characters that need escaping before enclosing
55 // their containing string in quotes.
56 _SPECIAL_CHARS = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
57 // Character substitution map for common escapes and special characters.
69 // Utility function used to determine how to serialize a variable.
72 return _allowable[t] || // number, string, boolean, undefined
73 _allowable[_toStr.call(o)] || // Number, String, Boolean, Date
75 (o ? OBJECT : NULL) : // object, array, null, misc natives
76 UNDEFINED); // function, unknown
79 // Escapes a special character to a safe Unicode representation
82 _CHARS[c] = '\\u'+('0000'+(+(c.charCodeAt(0))).toString(16)).slice(-4);
87 // Enclose escaped strings in quotes
89 return QUOTE + s.replace(_SPECIAL_CHARS, _char) + QUOTE;
92 // Adds the provided space to the beginning of every line in the input string
93 function _indent(s,space) {
94 return s.replace(/^/gm, space);
97 // JavaScript implementation of stringify (see API declaration of stringify)
98 function _stringify(o,w,space) {
99 if (o === undefined) {
103 var replacer = isFunction(w) ? w : null,
104 format = _toStr.call(space).match(/String|Number/) || [],
105 _date = Y.JSON.dateToString,
109 if (replacer || !isArray(w)) {
113 // Ensure whitelist keys are unique (bug 2110391)
116 for (i = 0, len = w.length; i < len; ++i) {
122 // Per the spec, strings are truncated to 10 characters and numbers
123 // are converted to that number of spaces (max 10)
124 space = format[0] === 'Number' ?
125 new Array(Math.min(Math.max(0,space),10)+1).join(" ") :
126 (space || EMPTY).slice(0,10);
128 function _serialize(h,key) {
132 colon = space ? COLON_SP : COLON,
135 // Per the ECMA 5 spec, toJSON is applied before the replacer is
136 // called. Also per the spec, Date.prototype.toJSON has been added, so
137 // Date instances should be serialized prior to exposure to the
138 // replacer. I disagree with this decision, but the spec is the spec.
139 if (isObject(value) && isFunction(value.toJSON)) {
140 value = value.toJSON(key);
141 } else if (t === DATE) {
142 value = _date(value);
145 if (isFunction(replacer)) {
146 value = replacer.call(h,key,value);
149 if (value !== h[key]) {
154 case DATE : // intentional fallthrough. Pre-replacer Dates are
155 // serialized in the toJSON stage. Dates here would
156 // have been produced by the replacer.
158 case STRING : return _string(value);
159 case NUMBER : return isFinite(value) ? value+EMPTY : NULL;
160 case BOOLEAN : return value+EMPTY;
161 case NULL : return NULL;
162 default : return undefined;
165 // Check for cyclical references in nested objects
166 for (i = stack.length - 1; i >= 0; --i) {
167 if (stack[i] === value) {
168 throw new Error("JSON.stringify. Cyclical reference");
172 arr = isArray(value);
174 // Add the object to the processing stack
178 for (i = value.length - 1; i >= 0; --i) {
179 a[i] = _serialize(value, i) || NULL;
182 // If whitelist provided, take only those keys
187 if (keys.hasOwnProperty(k)) {
188 v = _serialize(value, k);
190 a[i++] = _string(k) + colon + v;
196 // remove the array from the stack
199 if (space && a.length) {
201 OPEN_A + CR + _indent(a.join(COMMA_CR), space) + CR + CLOSE_A :
202 OPEN_O + CR + _indent(a.join(COMMA_CR), space) + CR + CLOSE_O;
205 OPEN_A + a.join(COMMA) + CLOSE_A :
206 OPEN_O + a.join(COMMA) + CLOSE_O;
211 return _serialize({'':o},'');
214 Y.mix(Y.namespace('JSON'),{
216 * Leverage native JSON stringify if the browser has a native
217 * implementation. In general, this is a good idea. See the Known Issues
218 * section in the JSON user guide for caveats. The default value is true
219 * for browsers with native JSON support.
221 * @property JSON.useNativeStringify
226 useNativeStringify : !!Native,
229 * Serializes a Date instance as a UTC date string. Used internally by
230 * stringify. Override this method if you need Dates serialized in a
233 * @method dateToString
234 * @param d {Date} The Date to serialize
235 * @return {String} stringified Date in UTC format YYYY-MM-DDTHH:mm:SSZ
238 dateToString : function (d) {
239 function _zeroPad(v) {
240 return v < 10 ? '0' + v : v;
243 return d.getUTCFullYear() + '-' +
244 _zeroPad(d.getUTCMonth() + 1) + '-' +
245 _zeroPad(d.getUTCDate()) + 'T' +
246 _zeroPad(d.getUTCHours()) + COLON +
247 _zeroPad(d.getUTCMinutes()) + COLON +
248 _zeroPad(d.getUTCSeconds()) + 'Z';
252 * <p>Converts an arbitrary value to a JSON string representation.</p>
254 * <p>Objects with cyclical references will trigger an exception.</p>
256 * <p>If a whitelist is provided, only matching object keys will be
257 * included. Alternately, a replacer function may be passed as the
258 * second parameter. This function is executed on every value in the
259 * input, and its return value will be used in place of the original value.
260 * This is useful to serialize specialized objects or class instances.</p>
262 * <p>If a positive integer or non-empty string is passed as the third
263 * parameter, the output will be formatted with carriage returns and
264 * indentation for readability. If a String is passed (such as "\t") it
265 * will be used once for each indentation level. If a number is passed,
266 * that number of spaces will be used.</p>
269 * @param o {MIXED} any arbitrary value to convert to JSON string
270 * @param w {Array|Function} (optional) whitelist of acceptable object
271 * keys to include, or a replacer function to modify the
272 * raw value before serialization
273 * @param ind {Number|String} (optional) indentation character or depth of
274 * spaces to format the output.
275 * @return {string} JSON string representation of the input
278 stringify : function (o,w,ind) {
279 return Native && Y.JSON.useNativeStringify ?
280 Native.stringify(o,w,ind) : _stringify(o,w,ind);