// json2.js // 2016-10-28 // 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. this file provides the es5 json capability to es3 systems. // if a project might run on ie8 or earlier, then this file should be included. // this file does nothing on es5 systems. // 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. // 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" or " "), // it contains the characters used to indent at each level. // 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()) + "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 the replacer parameter is an array of strings, 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 json representations, 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 json values. // json.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 // the indentation will be that many spaces. // example: // text = json.stringify(["e", {pluribus: "unum"}]); // // text is '["e",{"pluribus":"unum"}]' // text = json.stringify(["e", {pluribus: "unum"}], null, "\t"); // // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' // text = json.stringify([new date()], function (key, value) { // return this[key] instanceof date // ? "date(" + this[key] + ")" // : value; // }); // // text is '["date(---current time---)"]' // json.parse(text, reviver) // this method parses a json 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 = json.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; // }); // mydata = json.parse('["date(09/09/2001)"]', function (key, value) { // var d; // if (typeof value === "string" && // value.slice(0, 5) === "date(" && // value.slice(-1) === ")") { // d = new date(value.slice(5, -1)); // if (d) { // return d; // } // } // return value; // }); // this is a reference implementation. you are free to copy, modify, or // redistribute. /*jslint eval, for, this */ /*property json, apply, call, charcodeat, getutcdate, getutcfullyear, getutchours, getutcminutes, getutcmonth, getutcseconds, hasownproperty, join, lastindex, length, parse, prototype, push, replace, slice, stringify, test, tojson, tostring, valueof */ // create a json object only if one does not already exist. we create the // methods in a closure to avoid creating global variables. if (typeof json !== "object") { json = {}; } (function () { "use strict"; var rx_one = /^[\],:{}\s]*$/; var rx_two = /\\(?:["\\\/bfnrt]|u[0-9a-fa-f]{4})/g; var rx_three = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[ee][+\-]?\d+)?/g; var rx_four = /(?:^|:|,)(?:\s*\[)+/g; var rx_escapable = /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; var rx_dangerous = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; function f(n) { // format integers to have at least two digits. return n < 10 ? "0" + n : n; } function this_value() { return this.valueof(); } if (typeof date.prototype.tojson !== "function") { date.prototype.tojson = function () { return isfinite(this.valueof()) ? this.getutcfullyear() + "-" + f(this.getutcmonth() + 1) + "-" + f(this.getutcdate()) + "t" + f(this.getutchours()) + ":" + f(this.getutcminutes()) + ":" + f(this.getutcseconds()) + "z" : null; }; boolean.prototype.tojson = this_value; number.prototype.tojson = this_value; string.prototype.tojson = this_value; } var gap; var indent; var meta; var 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. rx_escapable.lastindex = 0; return rx_escapable.test(string) ? "\"" + string.replace(rx_escapable, function (a) { var c = meta[a]; return typeof c === "string" ? c : "\\u" + ("0000" + a.charcodeat(0).tostring(16)).slice(-4); }) + "\"" : "\"" + string + "\""; } function str(key, holder) { // produce a string from holder[key]. var i; // the loop counter. var k; // the member key. var v; // the member value. var length; var mind = gap; var partial; var value = holder[key]; // if the value has a tojson method, call it to obtain a replacement value. if (value && typeof value === "object" && typeof value.tojson === "function") { value = value.tojson(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": // json 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 "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 = []; // is the value an array? if (object.prototype.tostring.apply(value) === "[object array]") { // the value is an array. stringify every element. use null as a placeholder // for non-json 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 (rep && typeof rep === "object") { length = rep.length; for (i = 0; i < length; i += 1) { if (typeof rep[i] === "string") { k = rep[i]; v = str(k, value); if (v) { partial.push(quote(k) + ( gap ? ": " : ":" ) + v); } } } } else { // otherwise, iterate through all of the keys in the object. for (k in value) { if (object.prototype.hasownproperty.call(value, k)) { v = str(k, value); 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; } } // if the json object does not yet have a stringify method, give it one. if (typeof json.stringify !== "function") { meta = { // table of character substitutions "\b": "\\b", "\t": "\\t", "\n": "\\n", "\f": "\\f", "\r": "\\r", "\"": "\\\"", "\\": "\\\\" }; json.stringify = function (value, replacer, space) { // the stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a json 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 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 a replacer, it must be a function or an array. // otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== "function" && (typeof replacer !== "object" || typeof replacer.length !== "number")) { throw new error("json.stringify"); } // make a fake root object containing our value under the key of "". // return the result of stringifying the value. return str("", {"": value}); }; } // if the json object does not yet have a parse method, give it one. if (typeof json.parse !== "function") { json.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 json 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; var v; var value = holder[key]; if (value && typeof value === "object") { for (k in value) { if (object.prototype.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 four stages. in the first stage, we replace certain // unicode characters with escape sequences. javascript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = string(text); rx_dangerous.lastindex = 0; if (rx_dangerous.test(text)) { text = text.replace(rx_dangerous, function (a) { return "\\u" + ("0000" + a.charcodeat(0).tostring(16)).slice(-4); }); } // in the second stage, we run the text against regular expressions that look // for non-json 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 second stage into 4 regexp operations in order to work around // crippling inefficiencies in ie's and safari's regexp engines. first we // replace the json backslash pairs with "@" (a non-json 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 ( rx_one.test( text .replace(rx_two, "@") .replace(rx_three, "]") .replace(rx_four, "") ) ) { // in the third 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 fourth 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 json parseable, then a syntaxerror is thrown. throw new syntaxerror("json.parse"); }; } }());