/* http://www.json2.org/json22.js 2008-03-24 public domain. no warranty expressed or implied. use at your own risk. see http://www.json2.org/js.html this file creates a global json2 object containing three methods: stringify, parse, and quote. json2.stringify(value, replacer, space) value any javascript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects without a tojson2 method. it can be a function or an array. space an optional parameter that specifies the indentation of nested structures. if it is omitted, the text will be packed without extra whitespace. if it is a number, it will specify the number of spaces to indent at each level. if it is a string (such as '\t'), it contains the characters used to indent at each level. this method produces a json2 text from a javascript value. when an object value is found, if the object contains a tojson2 method, its tojson2 method will be called and the result will be stringified. a tojson2 method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. the tojson2 method will be passed the key associated with the value, and this will be bound to the object holding the key. this is the tojson2 method added to dates: function tojson2(key) { return this.getutcfullyear() + '-' + f(this.getutcmonth() + 1) + '-' + f(this.getutcdate()) + 't' + f(this.getutchours()) + ':' + f(this.getutcminutes()) + ':' + f(this.getutcseconds()) + 'z'; } you can provide an optional replacer method. it will be passed the key and value of each member, with this bound to the containing object. the value that is returned from your method will be serialized. if your method returns undefined, then the member will be excluded from the serialization. if no replacer parameter is provided, then a default replacer will be used: function replacer(key, value) { return object.hasownproperty.call(this, key) ? value : undefined; } the default replacer is passed the key and value for each item in the structure. it excludes inherited members. if the replacer parameter is an array, then it will be used to select the members to be serialized. it filters the results such that only members with keys listed in the replacer array are stringified. values that do not have json2 representaions, such as undefined or functions, will not be serialized. such values in objects will be dropped; in arrays they will be replaced with null. you can use a replacer function to replace those with json2 values. json2.stringify(undefined) returns undefined. the optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. if the space parameter is a non-empty string, then that string will be used for indentation. if the space parameter is a number, then then indentation will be that many spaces. example: text = json2.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = json2.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' json2.parse(text, reviver) this method parses a json2 text to produce an object or array. it can throw a syntaxerror exception. the optional reviver parameter is a function that can filter and transform the results. it receives each of the keys and values, and its return value is used instead of the original value. if it returns what it received, then the structure is not modified. if it returns undefined then the member is deleted. example: // parse the text. values that look like iso date strings will // be converted to date objects. mydata = json2.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})t(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)z$/.exec(value); if (a) { return new date(date.utc(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); json2.quote(text) this method wraps a string in quotes, escaping some characters as needed. this is a reference implementation. you are free to copy, modify, or redistribute. use your own copy. it is extremely unwise to load third party code into your pages. */ /*jslint regexp: true, forin: true, evil: true */ /*global json2 */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", json2, "\\", apply, call, charcodeat, floor, getutcdate, getutcfullyear, getutchours, getutcminutes, getutcmonth, getutcseconds, hasownproperty, join, length, parse, propertyisenumerable, prototype, push, quote, replace, stringify, test, tojson2, tostring */ if (!this.json2) { // create a json2 object only if one does not already exist. we create the // object in a closure to avoid global variables. json2 = function () { function f(n) { // format integers to have at least two digits. return n < 10 ? '0' + n : n; } date.prototype.tojson2 = function () { // eventually, this method will be based on the date.toisostring method. return this.getutcfullyear() + '-' + f(this.getutcmonth() + 1) + '-' + f(this.getutcdate()) + 't' + f(this.getutchours()) + ':' + f(this.getutcminutes()) + ':' + f(this.getutcseconds()) + 'z'; }; var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { // if the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // otherwise we must also replace the offending characters with safe escape // sequences. return escapeable.test(string) ? '"' + string.replace(escapeable, function (a) { var c = meta[a]; if (typeof c === 'string') { return c; } c = a.charcodeat(); return '\\u00' + math.floor(c / 16).tostring(16) + (c % 16).tostring(16); }) + '"' : '"' + string + '"'; } function str(key, holder) { // produce a string from holder[key]. var i, // the loop counter. k, // the member key. v, // the member value. length, mind = gap, partial, value = holder[key]; // if the value has a tojson2 method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.tojson2 === 'function') { value = value.tojson2(key); } // if we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // what happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // json2 numbers must be finite. encode non-finite numbers as null. return isfinite(value) ? string(value) : 'null'; case 'boolean': case 'null': // if the value is a boolean or null, convert it to a string. note: // typeof null does not produce 'null'. the case is included here in // the remote chance that this gets fixed someday. return string(value); // if the type is 'object', we might be dealing with an object or an array or // null. //case 'function': // return value.tostring(); case 'object': // due to a specification blunder in ecmascript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // if the object has a dontenum length property, we'll treat it as an array. if (typeof value.length === 'number' && !(value.propertyisenumerable('length'))) { // the object is an array. stringify every element. use null as a placeholder // for non-json2 values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // if the replacer is an array, use it to select the members to be stringified. if (typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value, rep); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // otherwise, iterate through all of the keys in the object. for (k in value) { v = str(k, value, rep); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } // join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // return the json2 object containing the stringify, parse, and quote methods. return { stringify: function (value, replacer, space) { // the stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a json2 text. the replacer can be a function // that can replace values, or an array of strings that will select the keys. // a default replacer method can be provided. use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; if (space) { // if the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // if the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } } // if there is no replacer parameter, use the default replacer. if (!replacer) { rep = function (key, value) { if (!object.hasownproperty.call(this, key)) { return undefined; } return value; }; // the replacer can be a function or an array. otherwise, throw an error. } else if (typeof replacer === 'function' || (typeof replacer === 'object' && typeof replacer.length === 'number')) { rep = replacer; } else { throw new error('json2.stringify'); } // make a fake root object containing our value under the key of ''. // return the result of stringifying the value. return str('', {'': value}); }, parse: function (text, reviver) { // the parse method takes a text and an optional reviver function, and returns // a javascript value if the text is a valid json2 text. var j; function walk(holder, key) { // the walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (object.hasownproperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // parsing happens in three stages. in the first stage, we run the text against // regular expressions that look for non-json2 patterns. we are especially // concerned with '()' and 'new' because they can cause invocation, and '=' // because it can cause mutation. but just to be safe, we want to reject all // unexpected forms. // we split the first stage into 4 regexp operations in order to work around // crippling inefficiencies in ie's and safari's regexp engines. first we // replace all backslash pairs with '@' (a non-json2 character). second, we // replace all simple value tokens with ']' characters. third, we delete all // open brackets that follow a colon or comma or that begin the text. finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. if that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/bfnrtu]/g, '@'). replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[ee][+\-]?\d+)?/g, ']'). replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // in the second stage we use the eval function to compile the text into a // javascript structure. the '{' operator is subject to a syntactic ambiguity // in javascript: it can begin a block or an object literal. we wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // in the optional third stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // if the text is not json2 parseable, then a syntaxerror is thrown. throw new syntaxerror('json2.parse'); }, quote: quote }; }(); }