1 /**
  2  * @fileOverview Douglas Crockford’s JSON parser and serializer.
  3  */
  4 
  5 /*
  6     http://www.JSON.org/json2.js
  7     2011-02-23
  8 
  9     Public Domain.
 10 
 11     NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
 12 
 13     See http://www.JSON.org/js.html
 14 
 15 
 16     This code should be minified before deployment.
 17     See http://javascript.crockford.com/jsmin.html
 18 
 19     USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
 20     NOT CONTROL.
 21 
 22 
 23     This file creates a global JSON object containing two methods: stringify
 24     and parse.
 25 
 26         JSON.stringify(value, replacer, space)
 27             value       any JavaScript value, usually an object or array.
 28 
 29             replacer    an optional parameter that determines how object
 30                         values are stringified for objects. It can be a
 31                         function or an array of strings.
 32 
 33             space       an optional parameter that specifies the indentation
 34                         of nested structures. If it is omitted, the text will
 35                         be packed without extra whitespace. If it is a number,
 36                         it will specify the number of spaces to indent at each
 37                         level. If it is a string (such as '\t' or ' '),
 38                         it contains the characters used to indent at each level.
 39 
 40             This method produces a JSON text from a JavaScript value.
 41 
 42             When an object value is found, if the object contains a toJSON
 43             method, its toJSON method will be called and the result will be
 44             stringified. A toJSON method does not serialize: it returns the
 45             value represented by the name/value pair that should be serialized,
 46             or undefined if nothing should be serialized. The toJSON method
 47             will be passed the key associated with the value, and this will be
 48             bound to the value
 49 
 50             For example, this would serialize Dates as ISO strings.
 51 
 52                 Date.prototype.toJSON = function (key) {
 53                     function f(n) {
 54                         // Format integers to have at least two digits.
 55                         return n < 10 ? '0' + n : n;
 56                     }
 57 
 58                     return this.getUTCFullYear()   + '-' +
 59                          f(this.getUTCMonth() + 1) + '-' +
 60                          f(this.getUTCDate())      + 'T' +
 61                          f(this.getUTCHours())     + ':' +
 62                          f(this.getUTCMinutes())   + ':' +
 63                          f(this.getUTCSeconds())   + 'Z';
 64                 };
 65 
 66             You can provide an optional replacer method. It will be passed the
 67             key and value of each member, with this bound to the containing
 68             object. The value that is returned from your method will be
 69             serialized. If your method returns undefined, then the member will
 70             be excluded from the serialization.
 71 
 72             If the replacer parameter is an array of strings, then it will be
 73             used to select the members to be serialized. It filters the results
 74             such that only members with keys listed in the replacer array are
 75             stringified.
 76 
 77             Values that do not have JSON representations, such as undefined or
 78             functions, will not be serialized. Such values in objects will be
 79             dropped; in arrays they will be replaced with null. You can use
 80             a replacer function to replace those with JSON values.
 81             JSON.stringify(undefined) returns undefined.
 82 
 83             The optional space parameter produces a stringification of the
 84             value that is filled with line breaks and indentation to make it
 85             easier to read.
 86 
 87             If the space parameter is a non-empty string, then that string will
 88             be used for indentation. If the space parameter is a number, then
 89             the indentation will be that many spaces.
 90 
 91             Example:
 92 
 93             text = JSON.stringify(['e', {pluribus: 'unum'}]);
 94             // text is '["e",{"pluribus":"unum"}]'
 95 
 96 
 97             text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
 98             // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
 99 
100             text = JSON.stringify([new Date()], function (key, value) {
101                 return this[key] instanceof Date ?
102                     'Date(' + this[key] + ')' : value;
103             });
104             // text is '["Date(---current time---)"]'
105 
106 
107         JSON.parse(text, reviver)
108             This method parses a JSON text to produce an object or array.
109             It can throw a SyntaxError exception.
110 
111             The optional reviver parameter is a function that can filter and
112             transform the results. It receives each of the keys and values,
113             and its return value is used instead of the original value.
114             If it returns what it received, then the structure is not modified.
115             If it returns undefined then the member is deleted.
116 
117             Example:
118 
119             // Parse the text. Values that look like ISO date strings will
120             // be converted to Date objects.
121 
122             myData = JSON.parse(text, function (key, value) {
123                 var a;
124                 if (typeof value === 'string') {
125                     a =
126 /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
127                     if (a) {
128                         return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
129                             +a[5], +a[6]));
130                     }
131                 }
132                 return value;
133             });
134 
135             myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
136                 var d;
137                 if (typeof value === 'string' &&
138                         value.slice(0, 5) === 'Date(' &&
139                         value.slice(-1) === ')') {
140                     d = new Date(value.slice(5, -1));
141                     if (d) {
142                         return d;
143                     }
144                 }
145                 return value;
146             });
147 
148 
149     This is a reference implementation. You are free to copy, modify, or
150     redistribute.
151 */
152 
153 /*jslint evil: true, strict: false, regexp: false */
154 
155 /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
156     call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
157     getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
158     lastIndex, length, parse, prototype, push, replace, slice, stringify,
159     test, toJSON, toString, valueOf
160 */
161 
162 
163 // Create a JSON object only if one does not already exist. We create the
164 // methods in a closure to avoid creating global variables.
165 
166 var JSON;
167 if (!JSON) {
168     JSON = {};
169 }
170 
171 (function () {
172     "use strict";
173 
174     function f(n) {
175         // Format integers to have at least two digits.
176         return n < 10 ? '0' + n : n;
177     }
178 
179     if (typeof Date.prototype.toJSON !== 'function') {
180 
181         Date.prototype.toJSON = function (key) {
182 
183             return isFinite(this.valueOf()) ?
184                 this.getUTCFullYear()     + '-' +
185                 f(this.getUTCMonth() + 1) + '-' +
186                 f(this.getUTCDate())      + 'T' +
187                 f(this.getUTCHours())     + ':' +
188                 f(this.getUTCMinutes())   + ':' +
189                 f(this.getUTCSeconds())   + 'Z' : null;
190         };
191 
192         String.prototype.toJSON      =
193             Number.prototype.toJSON  =
194             Boolean.prototype.toJSON = function (key) {
195                 return this.valueOf();
196             };
197     }
198 
199     var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
200         escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
201         gap,
202         indent,
203         meta = {    // table of character substitutions
204             '\b': '\\b',
205             '\t': '\\t',
206             '\n': '\\n',
207             '\f': '\\f',
208             '\r': '\\r',
209             '"' : '\\"',
210             '\\': '\\\\'
211         },
212         rep;
213 
214 
215     function quote(string) {
216 
217 // If the string contains no control characters, no quote characters, and no
218 // backslash characters, then we can safely slap some quotes around it.
219 // Otherwise we must also replace the offending characters with safe escape
220 // sequences.
221 
222         escapable.lastIndex = 0;
223         return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
224             var c = meta[a];
225             return typeof c === 'string' ? c :
226                 '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
227         }) + '"' : '"' + string + '"';
228     }
229 
230 
231     function str(key, holder) {
232 
233 // Produce a string from holder[key].
234 
235         var i,          // The loop counter.
236             k,          // The member key.
237             v,          // The member value.
238             length,
239             mind = gap,
240             partial,
241             value = holder[key];
242 
243 // If the value has a toJSON method, call it to obtain a replacement value.
244 
245         if (value && typeof value === 'object' &&
246                 typeof value.toJSON === 'function') {
247             value = value.toJSON(key);
248         }
249 
250 // If we were called with a replacer function, then call the replacer to
251 // obtain a replacement value.
252 
253         if (typeof rep === 'function') {
254             value = rep.call(holder, key, value);
255         }
256 
257 // What happens next depends on the value's type.
258 
259         switch (typeof value) {
260         case 'string':
261             return quote(value);
262 
263         case 'number':
264 
265 // JSON numbers must be finite. Encode non-finite numbers as null.
266 
267             return isFinite(value) ? String(value) : 'null';
268 
269         case 'boolean':
270         case 'null':
271 
272 // If the value is a boolean or null, convert it to a string. Note:
273 // typeof null does not produce 'null'. The case is included here in
274 // the remote chance that this gets fixed someday.
275 
276             return String(value);
277 
278 // If the type is 'object', we might be dealing with an object or an array or
279 // null.
280 
281         case 'object':
282 
283 // Due to a specification blunder in ECMAScript, typeof null is 'object',
284 // so watch out for that case.
285 
286             if (!value) {
287                 return 'null';
288             }
289 
290 // Make an array to hold the partial results of stringifying this object value.
291 
292             gap += indent;
293             partial = [];
294 
295 // Is the value an array?
296 
297             if (Object.prototype.toString.apply(value) === '[object Array]') {
298 
299 // The value is an array. Stringify every element. Use null as a placeholder
300 // for non-JSON values.
301 
302                 length = value.length;
303                 for (i = 0; i < length; i += 1) {
304                     partial[i] = str(i, value) || 'null';
305                 }
306 
307 // Join all of the elements together, separated with commas, and wrap them in
308 // brackets.
309 
310                 v = partial.length === 0 ? '[]' : gap ?
311                     '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' :
312                     '[' + partial.join(',') + ']';
313                 gap = mind;
314                 return v;
315             }
316 
317 // If the replacer is an array, use it to select the members to be stringified.
318 
319             if (rep && typeof rep === 'object') {
320                 length = rep.length;
321                 for (i = 0; i < length; i += 1) {
322                     if (typeof rep[i] === 'string') {
323                         k = rep[i];
324                         v = str(k, value);
325                         if (v) {
326                             partial.push(quote(k) + (gap ? ': ' : ':') + v);
327                         }
328                     }
329                 }
330             } else {
331 
332 // Otherwise, iterate through all of the keys in the object.
333 
334                 for (k in value) {
335                     if (Object.prototype.hasOwnProperty.call(value, k)) {
336                         v = str(k, value);
337                         if (v) {
338                             partial.push(quote(k) + (gap ? ': ' : ':') + v);
339                         }
340                     }
341                 }
342             }
343 
344 // Join all of the member texts together, separated with commas,
345 // and wrap them in braces.
346 
347             v = partial.length === 0 ? '{}' : gap ?
348                 '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' :
349                 '{' + partial.join(',') + '}';
350             gap = mind;
351             return v;
352         }
353     }
354 
355 // If the JSON object does not yet have a stringify method, give it one.
356 
357     if (typeof JSON.stringify !== 'function') {
358         JSON.stringify = function (value, replacer, space) {
359 
360 // The stringify method takes a value and an optional replacer, and an optional
361 // space parameter, and returns a JSON text. The replacer can be a function
362 // that can replace values, or an array of strings that will select the keys.
363 // A default replacer method can be provided. Use of the space parameter can
364 // produce text that is more easily readable.
365 
366             var i;
367             gap = '';
368             indent = '';
369 
370 // If the space parameter is a number, make an indent string containing that
371 // many spaces.
372 
373             if (typeof space === 'number') {
374                 for (i = 0; i < space; i += 1) {
375                     indent += ' ';
376                 }
377 
378 // If the space parameter is a string, it will be used as the indent string.
379 
380             } else if (typeof space === 'string') {
381                 indent = space;
382             }
383 
384 // If there is a replacer, it must be a function or an array.
385 // Otherwise, throw an error.
386 
387             rep = replacer;
388             if (replacer && typeof replacer !== 'function' &&
389                     (typeof replacer !== 'object' ||
390                     typeof replacer.length !== 'number')) {
391                 throw new Error('JSON.stringify');
392             }
393 
394 // Make a fake root object containing our value under the key of ''.
395 // Return the result of stringifying the value.
396 
397             return str('', {'': value});
398         };
399     }
400 
401 
402 // If the JSON object does not yet have a parse method, give it one.
403 
404     if (typeof JSON.parse !== 'function') {
405         JSON.parse = function (text, reviver) {
406 
407 // The parse method takes a text and an optional reviver function, and returns
408 // a JavaScript value if the text is a valid JSON text.
409 
410             var j;
411 
412             function walk(holder, key) {
413 
414 // The walk method is used to recursively walk the resulting structure so
415 // that modifications can be made.
416 
417                 var k, v, value = holder[key];
418                 if (value && typeof value === 'object') {
419                     for (k in value) {
420                         if (Object.prototype.hasOwnProperty.call(value, k)) {
421                             v = walk(value, k);
422                             if (v !== undefined) {
423                                 value[k] = v;
424                             } else {
425                                 delete value[k];
426                             }
427                         }
428                     }
429                 }
430                 return reviver.call(holder, key, value);
431             }
432 
433 
434 // Parsing happens in four stages. In the first stage, we replace certain
435 // Unicode characters with escape sequences. JavaScript handles many characters
436 // incorrectly, either silently deleting them, or treating them as line endings.
437 
438             text = String(text);
439             cx.lastIndex = 0;
440             if (cx.test(text)) {
441                 text = text.replace(cx, function (a) {
442                     return '\\u' +
443                         ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
444                 });
445             }
446 
447 // In the second stage, we run the text against regular expressions that look
448 // for non-JSON patterns. We are especially concerned with '()' and 'new'
449 // because they can cause invocation, and '=' because it can cause mutation.
450 // But just to be safe, we want to reject all unexpected forms.
451 
452 // We split the second stage into 4 regexp operations in order to work around
453 // crippling inefficiencies in IE's and Safari's regexp engines. First we
454 // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
455 // replace all simple value tokens with ']' characters. Third, we delete all
456 // open brackets that follow a colon or comma or that begin the text. Finally,
457 // we look to see that the remaining characters are only whitespace or ']' or
458 // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
459 
460             if (/^[\],:{}\s]*$/
461                     .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
462                         .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
463                         .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
464 
465 // In the third stage we use the eval function to compile the text into a
466 // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
467 // in JavaScript: it can begin a block or an object literal. We wrap the text
468 // in parens to eliminate the ambiguity.
469 
470                 j = eval('(' + text + ')');
471 
472 // In the optional fourth stage, we recursively walk the new structure, passing
473 // each name/value pair to a reviver function for possible transformation.
474 
475                 return typeof reviver === 'function' ?
476                     walk({'': j}, '') : j;
477             }
478 
479 // If the text is not JSON parseable, then a SyntaxError is thrown.
480 
481             throw new SyntaxError('JSON.parse');
482         };
483     }
484 }());
485 
486 
487 // Do not enumerate the new JSON methods.
488 // (These lines are not included in the original code by Crockford.)
489 Object.prototype.dontEnum("toJSONString");
490 Object.prototype.dontEnum("parseJSON");
491 
492 /**
493  * Create a JSONP-compatible response from the callback name and the desired data.
494  * @param {String} callback The name of the JSONP callback method
495  * @param {Object} data An arbitrary JavaScript object
496  */
497 JSON.pad = function(data, callback) {
498    if (!callback) {
499       return;
500    }
501    return callback + "(" + JSON.stringify(data) + ")";
502 }
503 
504 /**
505  * Send a JSONP-compatible response if a the request contains callback data.
506  * This works out-of-the-box with jQuery but can be customized using the key argument.
507  * @param {Object} data An arbitrary JavaScript object
508  * @param {String} key The name of the property in req.data containing the JSONP callback method name
509  * @param {Boolean} resume Switch to define whether further processing should be continued or not
510  */
511 JSON.sendPaddedResponse = function(data, key, resume) {
512    var callback = req.data[key || "callback"];
513    if (callback) {
514       res.contentType = "text/javascript";
515       res.write(JSON.pad(data, callback));
516       resume || res.stop();
517    }
518    return;
519 }
520