/* http://www.JSON.org/json2.js 2011-02-23 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED.

USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.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. It can be a function or an array of strings. 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' or ' '), it contains the characters used to indent at each level.

space

This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON 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 toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() f(this.getUTCMonth() + 1) f(this.getUTCDate()) f(this.getUTCHours()) f(this.getUTCMinutes()) f(this.getUTCSeconds()) }; + + + + + + '-' + '-' + 'T' + ':' + ':' + 'Z';

value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value. myData = JSON. Example: // Parse the text.stringify(['e'. then it will be used to select the members to be serialized.\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.parse(text. If it returns what it received. If the space parameter is a number. You can use a replacer function to replace those with JSON values.stringify([new Date()]. then the structure is not modified. if (typeof value === 'string') { . null. Values that look like ISO date strings will // be converted to Date objects. then the indentation will be that many spaces.stringify(undefined) returns undefined. will not be serialized. JSON. If the space parameter is a non-empty string. {pluribus: 'unum'}]. '\t'). and its return value is used instead of the original value. It can throw a SyntaxError exception. in arrays they will be replaced with null.You can provide an optional replacer method. If the replacer parameter is an array of strings. }). {pluribus: 'unum'}]). Values that do not have JSON representations. with this bound to the containing object. then that string will be used for indentation. The optional reviver parameter is a function that can filter and transform the results.{"pluribus":"unum"}]' text = JSON. // text is '["e". such as undefined or functions. It will be passed the key and value of each member. It receives each of the keys and values. function (key. reviver) This method parses a JSON text to produce an object or array.parse(text. Such values in objects will be dropped. // text is '["Date(---current time---)"]' JSON. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. value) { var a. // text is '[\n\t"e". function (key.stringify(['e'. If it returns undefined then the member is deleted. The value that is returned from your method will be serialized. If your method returns undefined. It filters the results such that only members with keys listed in the replacer array are stringified. Example: text = JSON. then the member will be excluded from the serialization.

replace. +a[3]. join. +a[6])). modify.toJSON = function (key) { return isFinite(this. "\f". or redistribute.1. getUTCMinutes.UTC(+a[1]. +a[2] .valueOf()) ? this. +a[4]. getUTCMonth. hasOwnProperty. toJSON. strict: false. getUTCFullYear. }). "\\". }). regexp: false */ /*members "". if (d) { return d.toJSON !== 'function') { Date. getUTCHours. } (function () { "use strict". prototype. if (!JSON) { JSON = {}. You are free to copy. stringify.slice(-1) === ')') { d = new Date(value. We create the // methods in a closure to avoid creating global variables. toString. +a[5]. "\n". getUTCDate.a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\. if (typeof value === 'string' && value. getUTCSeconds. -1)). test. } } return value. value) { var d. push. } } return value. var JSON.getUTCFullYear() + '-' + . "\t".exec(value). } if (typeof Date. return n < 10 ? '0' + n : n.slice(0. "\r". valueOf */ // Create a JSON object only if one does not already exist. apply.prototype. 5) === 'Date(' && value. function f(n) { // Format integers to have at least two digits. if (a) { return new Date(Date. length.slice(5. slice. parse.prototype. */ /*jslint evil: true. "\b".parse('["Date(09/09/2001)"]'. "\"". myData = JSON. JSON. charCodeAt.\d*)?)Z$/. lastIndex. call. function (key. This is a reference implementation.

Otherwise we must also replace the offending characters with safe escape sequences.prototype. indent. } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u 202f\u2060-\u206f\ufeff\ufff0-\uffff]/g. holder) { // Produce a string from holder[key]. String. . function quote(string) { // // // // If the string contains no control characters.replace(escapable.toJSON = Number. partial. rep. gap.toJSON = function (key) { return this.getUTCMinutes()) f(this. '\r': '\\r'. // The member value. '\t': '\\t'.lastIndex = 0.valueOf().test(string) ? '"' + string. function (a) { var c = meta[a]. // The loop counter. '\n': '\\n'.getUTCDate()) f(this.toJSON = Boolean. value = holder[key].f(this. '\\': '\\\\' }. meta = { // table of character substitutions '\b': '\\b'. '\f': '\\f'.getUTCSeconds()) }. then we can safely slap some quotes around it.prototype. k.slice(-4). v. and no backslash characters. escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b 5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g. '"' : '\\"'. return typeof c === 'string' ? c : '\\u' + ('0000' + a. + + + + + '-' 'T' ':' ':' 'Z' + + + + : null.prototype. } function str(key. }) + '"' : '"' + string + '"'. // The member key. }.charCodeAt(0). return escapable. escapable.getUTCHours()) f(this.toString(16)). var i. no quote characters.getUTCMonth() + 1) f(this. length. mind = gap.

case 'number': // JSON numbers must be finite.toJSON === 'function') { value = value. if (!value) { return 'null'. value). Encode non-finite numbers as null. return String(value).// If the value has a toJSON method. Use null as a placeholder // for non-JSON values. if (value && typeof value === 'object' && typeof value.toString.prototype.apply(value) === '[object Array]') { // The value is an array. . partial = [].toJSON(key). // Is the value an array? if (Object. switch (typeof value) { case 'string': return quote(value). } // What happens next depends on the value's type.call(holder. if (typeof rep === 'function') { value = rep. Stringify every element. Note: // typeof null does not produce 'null'. we might be dealing with an object or an array or // null. } // If we were called with a replacer function. case 'boolean': case 'null': // If the value is a boolean or null. then call the replacer to // obtain a replacement value. The case is included here in // the remote chance that this gets fixed someday. // so watch out for that case. gap += indent. return isFinite(value) ? String(value) : 'null'. key. convert it to a string. call it to obtain a replacement value. // If the type is 'object'. typeof null is 'object'. case 'object': // Due to a specification blunder in ECMAScript. } // Make an array to hold the partial results of stringifying this object value.

') + ']'. and wrap them in // brackets. use it to select the members to be stringified.push(quote(k) + (gap ? ': ' : ':') + v). give it one. for (i = 0. v = partial. i += 1) { partial[i] = str(i.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join('. if (v) { partial. } // If the replacer is an array. i += 1) { (typeof rep[i] === 'string') { k = rep[i].push(quote(k) + (gap ? ': ' : ':') + v). return v. replacer.join('. separated with commas. space) { // The stringify method takes a value and an optional replacer.join('.stringify = function (value.length. iterate through all of the keys in the object. // and wrap them in braces. return v.call(value. } } // If the JSON object does not yet have a stringify method. k)) { v = str(k. i < length. gap = mind. value). = 0.prototype.\n' + gap) + '\n' + mind + '}' : '{' + partial. if (v) { partial. separated with commas. if (rep && length for (i if typeof rep === 'object') { = rep. } // Join all of the elements together.join('. for (k in value) { if (Object.stringify !== 'function') { JSON. value) 'null'.') + '}'. v = partial. i < length.length = value.length === 0 ? '{}' : gap ? '{\n' + gap + partial. v = str(k. } } } } // Join all of the member texts together.hasOwnProperty.length. gap = mind. } } } } else { // Otherwise. and an optional . value). if (typeof JSON.\n' + gap) + '\n' + mind + ']' : '[' + partial.

} // Make a fake root object containing our value under the key of ''. i < space. and returns // a JavaScript value if the text is a valid JSON text. // Otherwise.parse !== 'function') { JSON. and returns a JSON text. give it one. gap = ''. k)) { . }. reviver) { // The parse method takes a text and an optional reviver function. value = holder[key]. i += 1) { indent += ' '. v. } // If the space parameter is a string. indent = ''.call(value. // If the space parameter is a number. if (value && typeof value === 'object') { for (k in value) { if (Object.// // // // space parameter. key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made.parse = function (text. A default replacer method can be provided. var j. var k. } // If there is a replacer. } // If the JSON object does not yet have a parse method. it must be a function or an array. The replacer can be a function that can replace values. if (typeof JSON. throw an error. it will be used as the indent string. if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' typeof replacer. rep = replacer.prototype. function walk(holder. } else if (typeof space === 'string') { indent = space. or an array of strings that will select the keys.length !== 'number')) { throw new Error('JSON. Use of the space parameter can produce text that is more easily readable.hasOwnProperty. // Return the result of stringifying the value. return str(''.stringify'). make an indent string containing that // many spaces. {'': value}). var i. if (typeof space === 'number') { for (i = 0.

} // // // // // // // // // // // In the second stage.test(text. then the text is safe for eval. } else { delete value[k].slice(-4). we look to see that the remaining characters are only whitespace or ']' or '.replace(/"[^"\\\n\r]*" true false null -?\d+(?:\. we recursively walk the new structure. '') : j. k). or treating them as line endings.replace(/\\(?:["\\\/bfnrt] u[0-9a-fA-F]{4})/g. We are especially concerned with '()' and 'new' because they can cause invocation.)(?:\s*\[)+/g. text = String(text).' or ':' or '{' or '}'. we run the text against regular expressions that look for non-JSON patterns.toString(16)). First we replace the JSON backslash pairs with '@' (a non-JSON character). '@ ') . we replace certain // Unicode characters with escape sequences.charCodeAt(0). we want to reject all unexpected forms. and '=' because it can cause mutation. if (cx.v = walk(value. } // Parsing happens in four stages. } .:{}\s]*$/ . if (/^[\]. we replace all simple value tokens with ']' characters. we delete all open brackets that follow a colon or comma or that begin the text. If that is so. j = eval('(' + text + ')').call(holder.replace(/(?:^ : . In the first stage. // In the optional fourth stage. key. The '{' operator is subject to a syntactic ambiguity in JavaScript: it can begin a block or an object literal. if (v !== undefined) { value[k] = v. return typeof reviver === 'function' ? walk({'': j}. either silently deleting them. ']') . We wrap the text in parens to eliminate the ambiguity. ''))) { // // // // In the third stage we use the eval function to compile the text into a JavaScript structure. } } } } return reviver. But just to be safe. Second. JavaScript handles many characters // incorrectly. Finally. Third.\d*)?( ?:[eE][+\-]?\d+)?/g. }). value).replace(cx.lastIndex = 0. cx. function (a) { return '\\u' + ('0000' + a.test(text)) { text = text. We split the second stage into 4 regexp operations in order to work around crippling inefficiencies in IE's and Safari's regexp engines. passing // each name/value pair to a reviver function for possible transformation.

throw new SyntaxError('JSON. . then a SyntaxError is thrown.parse').// If the text is not JSON parseable. }. } }()).

Sign up to vote on this title
UsefulNot useful