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