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