rlm@90: rlm@90: /* rlm@90: http://www.JSON.org/json2.js rlm@90: 2010-03-20 rlm@90: rlm@90: Public Domain. rlm@90: rlm@90: NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. rlm@90: rlm@90: See http://www.JSON.org/js.html rlm@90: rlm@90: rlm@90: This code should be minified before deployment. rlm@90: See http://javascript.crockford.com/jsmin.html rlm@90: rlm@90: USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO rlm@90: NOT CONTROL. rlm@90: rlm@90: rlm@90: This file creates a global JSON object containing two methods: stringify rlm@90: and parse. rlm@90: rlm@90: JSON.stringify(value, replacer, space) rlm@90: value any JavaScript value, usually an object or array. rlm@90: rlm@90: replacer an optional parameter that determines how object rlm@90: values are stringified for objects. It can be a rlm@90: function or an array of strings. rlm@90: rlm@90: space an optional parameter that specifies the indentation rlm@90: of nested structures. If it is omitted, the text will rlm@90: be packed without extra whitespace. If it is a number, rlm@90: it will specify the number of spaces to indent at each rlm@90: level. If it is a string (such as '\t' or ' '), rlm@90: it contains the characters used to indent at each level. rlm@90: rlm@90: This method produces a JSON text from a JavaScript value. rlm@90: rlm@90: When an object value is found, if the object contains a toJSON rlm@90: method, its toJSON method will be called and the result will be rlm@90: stringified. A toJSON method does not serialize: it returns the rlm@90: value represented by the name/value pair that should be serialized, rlm@90: or undefined if nothing should be serialized. The toJSON method rlm@90: will be passed the key associated with the value, and this will be rlm@90: bound to the value rlm@90: rlm@90: For example, this would serialize Dates as ISO strings. rlm@90: rlm@90: Date.prototype.toJSON = function (key) { rlm@90: function f(n) { rlm@90: // Format integers to have at least two digits. rlm@90: return n < 10 ? '0' + n : n; rlm@90: } rlm@90: rlm@90: return this.getUTCFullYear() + '-' + rlm@90: f(this.getUTCMonth() + 1) + '-' + rlm@90: f(this.getUTCDate()) + 'T' + rlm@90: f(this.getUTCHours()) + ':' + rlm@90: f(this.getUTCMinutes()) + ':' + rlm@90: f(this.getUTCSeconds()) + 'Z'; rlm@90: }; rlm@90: rlm@90: You can provide an optional replacer method. It will be passed the rlm@90: key and value of each member, with this bound to the containing rlm@90: object. The value that is returned from your method will be rlm@90: serialized. If your method returns undefined, then the member will rlm@90: be excluded from the serialization. rlm@90: rlm@90: If the replacer parameter is an array of strings, then it will be rlm@90: used to select the members to be serialized. It filters the results rlm@90: such that only members with keys listed in the replacer array are rlm@90: stringified. rlm@90: rlm@90: Values that do not have JSON representations, such as undefined or rlm@90: functions, will not be serialized. Such values in objects will be rlm@90: dropped; in arrays they will be replaced with null. You can use rlm@90: a replacer function to replace those with JSON values. rlm@90: JSON.stringify(undefined) returns undefined. rlm@90: rlm@90: The optional space parameter produces a stringification of the rlm@90: value that is filled with line breaks and indentation to make it rlm@90: easier to read. rlm@90: rlm@90: If the space parameter is a non-empty string, then that string will rlm@90: be used for indentation. If the space parameter is a number, then rlm@90: the indentation will be that many spaces. rlm@90: rlm@90: Example: rlm@90: rlm@90: text = JSON.stringify(['e', {pluribus: 'unum'}]); rlm@90: // text is '["e",{"pluribus":"unum"}]' rlm@90: rlm@90: rlm@90: text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); rlm@90: // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' rlm@90: rlm@90: text = JSON.stringify([new Date()], function (key, value) { rlm@90: return this[key] instanceof Date ? rlm@90: 'Date(' + this[key] + ')' : value; rlm@90: }); rlm@90: // text is '["Date(---current time---)"]' rlm@90: rlm@90: rlm@90: JSON.parse(text, reviver) rlm@90: This method parses a JSON text to produce an object or array. rlm@90: It can throw a SyntaxError exception. rlm@90: rlm@90: The optional reviver parameter is a function that can filter and rlm@90: transform the results. It receives each of the keys and values, rlm@90: and its return value is used instead of the original value. rlm@90: If it returns what it received, then the structure is not modified. rlm@90: If it returns undefined then the member is deleted. rlm@90: rlm@90: Example: rlm@90: rlm@90: // Parse the text. Values that look like ISO date strings will rlm@90: // be converted to Date objects. rlm@90: rlm@90: myData = JSON.parse(text, function (key, value) { rlm@90: var a; rlm@90: if (typeof value === 'string') { rlm@90: a = rlm@90: /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); rlm@90: if (a) { rlm@90: return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], rlm@90: +a[5], +a[6])); rlm@90: } rlm@90: } rlm@90: return value; rlm@90: }); rlm@90: rlm@90: myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { rlm@90: var d; rlm@90: if (typeof value === 'string' && rlm@90: value.slice(0, 5) === 'Date(' && rlm@90: value.slice(-1) === ')') { rlm@90: d = new Date(value.slice(5, -1)); rlm@90: if (d) { rlm@90: return d; rlm@90: } rlm@90: } rlm@90: return value; rlm@90: }); rlm@90: rlm@90: rlm@90: This is a reference implementation. You are free to copy, modify, or rlm@90: redistribute. rlm@90: */ rlm@90: rlm@90: /*jslint evil: true, strict: false */ rlm@90: rlm@90: /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, rlm@90: call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, rlm@90: getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, rlm@90: lastIndex, length, parse, prototype, push, replace, slice, stringify, rlm@90: test, toJSON, toString, valueOf rlm@90: */ rlm@90: rlm@90: rlm@90: // Create a JSON object only if one does not already exist. We create the rlm@90: // methods in a closure to avoid creating global variables. rlm@90: rlm@90: if (!this.JSON) { rlm@90: this.JSON = {}; rlm@90: } rlm@90: rlm@90: (function () { rlm@90: rlm@90: function f(n) { rlm@90: // Format integers to have at least two digits. rlm@90: return n < 10 ? '0' + n : n; rlm@90: } rlm@90: rlm@90: if (typeof Date.prototype.toJSON !== 'function') { rlm@90: rlm@90: Date.prototype.toJSON = function (key) { rlm@90: rlm@90: return isFinite(this.valueOf()) ? rlm@90: this.getUTCFullYear() + '-' + rlm@90: f(this.getUTCMonth() + 1) + '-' + rlm@90: f(this.getUTCDate()) + 'T' + rlm@90: f(this.getUTCHours()) + ':' + rlm@90: f(this.getUTCMinutes()) + ':' + rlm@90: f(this.getUTCSeconds()) + 'Z' : null; rlm@90: }; rlm@90: rlm@90: String.prototype.toJSON = rlm@90: Number.prototype.toJSON = rlm@90: Boolean.prototype.toJSON = function (key) { rlm@90: return this.valueOf(); rlm@90: }; rlm@90: } rlm@90: rlm@90: var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, rlm@90: escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, rlm@90: gap, rlm@90: indent, rlm@90: meta = { // table of character substitutions rlm@90: '\b': '\\b', rlm@90: '\t': '\\t', rlm@90: '\n': '\\n', rlm@90: '\f': '\\f', rlm@90: '\r': '\\r', rlm@90: '"' : '\\"', rlm@90: '\\': '\\\\' rlm@90: }, rlm@90: rep; rlm@90: rlm@90: rlm@90: function quote(string) { rlm@90: rlm@90: // If the string contains no control characters, no quote characters, and no rlm@90: // backslash characters, then we can safely slap some quotes around it. rlm@90: // Otherwise we must also replace the offending characters with safe escape rlm@90: // sequences. rlm@90: rlm@90: escapable.lastIndex = 0; rlm@90: return escapable.test(string) ? rlm@90: '"' + string.replace(escapable, function (a) { rlm@90: var c = meta[a]; rlm@90: return typeof c === 'string' ? c : rlm@90: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); rlm@90: }) + '"' : rlm@90: '"' + string + '"'; rlm@90: } rlm@90: rlm@90: rlm@90: function str(key, holder) { rlm@90: rlm@90: // Produce a string from holder[key]. rlm@90: rlm@90: var i, // The loop counter. rlm@90: k, // The member key. rlm@90: v, // The member value. rlm@90: length, rlm@90: mind = gap, rlm@90: partial, rlm@90: value = holder[key]; rlm@90: rlm@90: // If the value has a toJSON method, call it to obtain a replacement value. rlm@90: rlm@90: if (value && typeof value === 'object' && rlm@90: typeof value.toJSON === 'function') { rlm@90: value = value.toJSON(key); rlm@90: } rlm@90: rlm@90: // If we were called with a replacer function, then call the replacer to rlm@90: // obtain a replacement value. rlm@90: rlm@90: if (typeof rep === 'function') { rlm@90: value = rep.call(holder, key, value); rlm@90: } rlm@90: rlm@90: // What happens next depends on the value's type. rlm@90: rlm@90: switch (typeof value) { rlm@90: case 'string': rlm@90: return quote(value); rlm@90: rlm@90: case 'number': rlm@90: rlm@90: // JSON numbers must be finite. Encode non-finite numbers as null. rlm@90: rlm@90: return isFinite(value) ? String(value) : 'null'; rlm@90: rlm@90: case 'boolean': rlm@90: case 'null': rlm@90: rlm@90: // If the value is a boolean or null, convert it to a string. Note: rlm@90: // typeof null does not produce 'null'. The case is included here in rlm@90: // the remote chance that this gets fixed someday. rlm@90: rlm@90: return String(value); rlm@90: rlm@90: // If the type is 'object', we might be dealing with an object or an array or rlm@90: // null. rlm@90: rlm@90: case 'object': rlm@90: rlm@90: // Due to a specification blunder in ECMAScript, typeof null is 'object', rlm@90: // so watch out for that case. rlm@90: rlm@90: if (!value) { rlm@90: return 'null'; rlm@90: } rlm@90: rlm@90: // Make an array to hold the partial results of stringifying this object value. rlm@90: rlm@90: gap += indent; rlm@90: partial = []; rlm@90: rlm@90: // Is the value an array? rlm@90: rlm@90: if (Object.prototype.toString.apply(value) === '[object Array]') { rlm@90: rlm@90: // The value is an array. Stringify every element. Use null as a placeholder rlm@90: // for non-JSON values. rlm@90: rlm@90: length = value.length; rlm@90: for (i = 0; i < length; i += 1) { rlm@90: partial[i] = str(i, value) || 'null'; rlm@90: } rlm@90: rlm@90: // Join all of the elements together, separated with commas, and wrap them in rlm@90: // brackets. rlm@90: rlm@90: v = partial.length === 0 ? '[]' : rlm@90: gap ? '[\n' + gap + rlm@90: partial.join(',\n' + gap) + '\n' + rlm@90: mind + ']' : rlm@90: '[' + partial.join(',') + ']'; rlm@90: gap = mind; rlm@90: return v; rlm@90: } rlm@90: rlm@90: // If the replacer is an array, use it to select the members to be stringified. rlm@90: rlm@90: if (rep && typeof rep === 'object') { rlm@90: length = rep.length; rlm@90: for (i = 0; i < length; i += 1) { rlm@90: k = rep[i]; rlm@90: if (typeof k === 'string') { rlm@90: v = str(k, value); rlm@90: if (v) { rlm@90: partial.push(quote(k) + (gap ? ': ' : ':') + v); rlm@90: } rlm@90: } rlm@90: } rlm@90: } else { rlm@90: rlm@90: // Otherwise, iterate through all of the keys in the object. rlm@90: rlm@90: for (k in value) { rlm@90: if (Object.hasOwnProperty.call(value, k)) { rlm@90: v = str(k, value); rlm@90: if (v) { rlm@90: partial.push(quote(k) + (gap ? ': ' : ':') + v); rlm@90: } rlm@90: } rlm@90: } rlm@90: } rlm@90: rlm@90: // Join all of the member texts together, separated with commas, rlm@90: // and wrap them in braces. rlm@90: rlm@90: v = partial.length === 0 ? '{}' : rlm@90: gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + rlm@90: mind + '}' : '{' + partial.join(',') + '}'; rlm@90: gap = mind; rlm@90: return v; rlm@90: } rlm@90: } rlm@90: rlm@90: // If the JSON object does not yet have a stringify method, give it one. rlm@90: rlm@90: if (typeof JSON.stringify !== 'function') { rlm@90: JSON.stringify = function (value, replacer, space) { rlm@90: rlm@90: // The stringify method takes a value and an optional replacer, and an optional rlm@90: // space parameter, and returns a JSON text. The replacer can be a function rlm@90: // that can replace values, or an array of strings that will select the keys. rlm@90: // A default replacer method can be provided. Use of the space parameter can rlm@90: // produce text that is more easily readable. rlm@90: rlm@90: var i; rlm@90: gap = ''; rlm@90: indent = ''; rlm@90: rlm@90: // If the space parameter is a number, make an indent string containing that rlm@90: // many spaces. rlm@90: rlm@90: if (typeof space === 'number') { rlm@90: for (i = 0; i < space; i += 1) { rlm@90: indent += ' '; rlm@90: } rlm@90: rlm@90: // If the space parameter is a string, it will be used as the indent string. rlm@90: rlm@90: } else if (typeof space === 'string') { rlm@90: indent = space; rlm@90: } rlm@90: rlm@90: // If there is a replacer, it must be a function or an array. rlm@90: // Otherwise, throw an error. rlm@90: rlm@90: rep = replacer; rlm@90: if (replacer && typeof replacer !== 'function' && rlm@90: (typeof replacer !== 'object' || rlm@90: typeof replacer.length !== 'number')) { rlm@90: throw new Error('JSON.stringify'); rlm@90: } rlm@90: rlm@90: // Make a fake root object containing our value under the key of ''. rlm@90: // Return the result of stringifying the value. rlm@90: rlm@90: return str('', {'': value}); rlm@90: }; rlm@90: } rlm@90: rlm@90: rlm@90: // If the JSON object does not yet have a parse method, give it one. rlm@90: rlm@90: if (typeof JSON.parse !== 'function') { rlm@90: JSON.parse = function (text, reviver) { rlm@90: rlm@90: // The parse method takes a text and an optional reviver function, and returns rlm@90: // a JavaScript value if the text is a valid JSON text. rlm@90: rlm@90: var j; rlm@90: rlm@90: function walk(holder, key) { rlm@90: rlm@90: // The walk method is used to recursively walk the resulting structure so rlm@90: // that modifications can be made. rlm@90: rlm@90: var k, v, value = holder[key]; rlm@90: if (value && typeof value === 'object') { rlm@90: for (k in value) { rlm@90: if (Object.hasOwnProperty.call(value, k)) { rlm@90: v = walk(value, k); rlm@90: if (v !== undefined) { rlm@90: value[k] = v; rlm@90: } else { rlm@90: delete value[k]; rlm@90: } rlm@90: } rlm@90: } rlm@90: } rlm@90: return reviver.call(holder, key, value); rlm@90: } rlm@90: rlm@90: rlm@90: // Parsing happens in four stages. In the first stage, we replace certain rlm@90: // Unicode characters with escape sequences. JavaScript handles many characters rlm@90: // incorrectly, either silently deleting them, or treating them as line endings. rlm@90: rlm@90: text = String(text); rlm@90: cx.lastIndex = 0; rlm@90: if (cx.test(text)) { rlm@90: text = text.replace(cx, function (a) { rlm@90: return '\\u' + rlm@90: ('0000' + a.charCodeAt(0).toString(16)).slice(-4); rlm@90: }); rlm@90: } rlm@90: rlm@90: // In the second stage, we run the text against regular expressions that look rlm@90: // for non-JSON patterns. We are especially concerned with '()' and 'new' rlm@90: // because they can cause invocation, and '=' because it can cause mutation. rlm@90: // But just to be safe, we want to reject all unexpected forms. rlm@90: rlm@90: // We split the second stage into 4 regexp operations in order to work around rlm@90: // crippling inefficiencies in IE's and Safari's regexp engines. First we rlm@90: // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we rlm@90: // replace all simple value tokens with ']' characters. Third, we delete all rlm@90: // open brackets that follow a colon or comma or that begin the text. Finally, rlm@90: // we look to see that the remaining characters are only whitespace or ']' or rlm@90: // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. rlm@90: rlm@90: if (/^[\],:{}\s]*$/. rlm@90: test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@'). rlm@90: replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). rlm@90: replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { rlm@90: rlm@90: // In the third stage we use the eval function to compile the text into a rlm@90: // JavaScript structure. The '{' operator is subject to a syntactic ambiguity rlm@90: // in JavaScript: it can begin a block or an object literal. We wrap the text rlm@90: // in parens to eliminate the ambiguity. rlm@90: rlm@90: j = eval('(' + text + ')'); rlm@90: rlm@90: // In the optional fourth stage, we recursively walk the new structure, passing rlm@90: // each name/value pair to a reviver function for possible transformation. rlm@90: rlm@90: return typeof reviver === 'function' ? rlm@90: walk({'': j}, '') : j; rlm@90: } rlm@90: rlm@90: // If the text is not JSON parseable, then a SyntaxError is thrown. rlm@90: rlm@90: throw new SyntaxError('JSON.parse'); rlm@90: }; rlm@90: } rlm@90: }());