1 /* 2 json2.js 3 2011-10-19 4 5 Public Domain. 6 7 NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. 8 9 See http://www.JSON.org/js.html 10 11 12 This code should be minified before deployment. 13 See http://javascript.crockford.com/jsmin.html 14 15 USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO 16 NOT CONTROL. 17 18 19 This file creates a global JSON object containing two methods: stringify 20 and parse. 21 22 JSON.stringify(value, replacer, space) 23 value any JavaScript value, usually an object or array. 24 25 replacer an optional parameter that determines how object 26 values are stringified for objects. It can be a 27 function or an array of strings. 28 29 space an optional parameter that specifies the indentation 30 of nested structures. If it is omitted, the text will 31 be packed without extra whitespace. If it is a number, 32 it will specify the number of spaces to indent at each 33 level. If it is a string (such as '\t' or ' '), 34 it contains the characters used to indent at each level. 35 36 This method produces a JSON text from a JavaScript value. 37 38 When an object value is found, if the object contains a toJSON 39 method, its toJSON method will be called and the result will be 40 stringified. A toJSON method does not serialize: it returns the 41 value represented by the name/value pair that should be serialized, 42 or undefined if nothing should be serialized. The toJSON method 43 will be passed the key associated with the value, and this will be 44 bound to the value 45 46 For example, this would serialize Dates as ISO strings. 47 48 Date.prototype.toJSON = function (key) { 49 function f(n) { 50 // Format integers to have at least two digits. 51 return n < 10 ? '0' + n : n; 52 } 53 54 return this.getUTCFullYear() + '-' + 55 f(this.getUTCMonth() + 1) + '-' + 56 f(this.getUTCDate()) + 'T' + 57 f(this.getUTCHours()) + ':' + 58 f(this.getUTCMinutes()) + ':' + 59 f(this.getUTCSeconds()) + 'Z'; 60 }; 61 62 You can provide an optional replacer method. It will be passed the 63 key and value of each member, with this bound to the containing 64 object. The value that is returned from your method will be 65 serialized. If your method returns undefined, then the member will 66 be excluded from the serialization. 67 68 If the replacer parameter is an array of strings, then it will be 69 used to select the members to be serialized. It filters the results 70 such that only members with keys listed in the replacer array are 71 stringified. 72 73 Values that do not have JSON representations, such as undefined or 74 functions, will not be serialized. Such values in objects will be 75 dropped; in arrays they will be replaced with null. You can use 76 a replacer function to replace those with JSON values. 77 JSON.stringify(undefined) returns undefined. 78 79 The optional space parameter produces a stringification of the 80 value that is filled with line breaks and indentation to make it 81 easier to read. 82 83 If the space parameter is a non-empty string, then that string will 84 be used for indentation. If the space parameter is a number, then 85 the indentation will be that many spaces. 86 87 Example: 88 89 text = JSON.stringify(['e', {pluribus: 'unum'}]); 90 // text is '["e",{"pluribus":"unum"}]' 91 92 93 text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); 94 // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' 95 96 text = JSON.stringify([new Date()], function (key, value) { 97 return this[key] instanceof Date ? 98 'Date(' + this[key] + ')' : value; 99 }); 100 // text is '["Date(---current time---)"]' 101 102 103 JSON.parse(text, reviver) 104 This method parses a JSON text to produce an object or array. 105 It can throw a SyntaxError exception. 106 107 The optional reviver parameter is a function that can filter and 108 transform the results. It receives each of the keys and values, 109 and its return value is used instead of the original value. 110 If it returns what it received, then the structure is not modified. 111 If it returns undefined then the member is deleted. 112 113 Example: 114 115 // Parse the text. Values that look like ISO date strings will 116 // be converted to Date objects. 117 118 myData = JSON.parse(text, function (key, value) { 119 var a; 120 if (typeof value === 'string') { 121 a = 122 /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); 123 if (a) { 124 return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], 125 +a[5], +a[6])); 126 } 127 } 128 return value; 129 }); 130 131 myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { 132 var d; 133 if (typeof value === 'string' && 134 value.slice(0, 5) === 'Date(' && 135 value.slice(-1) === ')') { 136 d = new Date(value.slice(5, -1)); 137 if (d) { 138 return d; 139 } 140 } 141 return value; 142 }); 143 144 145 This is a reference implementation. You are free to copy, modify, or 146 redistribute. 147 */ 148 149 /*jslint evil: true, regexp: true */ 150 151 /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, 152 call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, 153 getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, 154 lastIndex, length, parse, prototype, push, replace, slice, stringify, 155 test, toJSON, toString, valueOf 156 */ 157 158 159 // Create a JSON object only if one does not already exist. We create the 160 // methods in a closure to avoid creating global variables. 161 162 var JSON; 163 if (!JSON) { 164 JSON = {}; 165 } 166 167 (function () { 168 'use strict'; 169 170 function f(n) { 171 // Format integers to have at least two digits. 172 return n < 10 ? '0' + n : n; 173 } 174 175 if (typeof Date.prototype.toJSON !== 'function') { 176 177 Date.prototype.toJSON = function (key) { 178 179 return isFinite(this.valueOf()) 180 ? this.getUTCFullYear() + '-' + 181 f(this.getUTCMonth() + 1) + '-' + 182 f(this.getUTCDate()) + 'T' + 183 f(this.getUTCHours()) + ':' + 184 f(this.getUTCMinutes()) + ':' + 185 f(this.getUTCSeconds()) + 'Z' 186 : null; 187 }; 188 189 String.prototype.toJSON = 190 Number.prototype.toJSON = 191 Boolean.prototype.toJSON = function (key) { 192 return this.valueOf(); 193 }; 194 } 195 196 var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, 197 escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, 198 gap, 199 indent, 200 meta = { // table of character substitutions 201 '\b': '\\b', 202 '\t': '\\t', 203 '\n': '\\n', 204 '\f': '\\f', 205 '\r': '\\r', 206 '"' : '\\"', 207 '\\': '\\\\' 208 }, 209 rep; 210 211 212 function quote(string) { 213 214 // If the string contains no control characters, no quote characters, and no 215 // backslash characters, then we can safely slap some quotes around it. 216 // Otherwise we must also replace the offending characters with safe escape 217 // sequences. 218 219 escapable.lastIndex = 0; 220 return escapable.test(string) ? '"' + string.replace(escapable, function (a) { 221 var c = meta[a]; 222 return typeof c === 'string' 223 ? c 224 : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); 225 }) + '"' : '"' + string + '"'; 226 } 227 228 229 function str(key, holder) { 230 231 // Produce a string from holder[key]. 232 233 var i, // The loop counter. 234 k, // The member key. 235 v, // The member value. 236 length, 237 mind = gap, 238 partial, 239 value = holder[key]; 240 241 // If the value has a toJSON method, call it to obtain a replacement value. 242 243 if (value && typeof value === 'object' && 244 typeof value.toJSON === 'function') { 245 value = value.toJSON(key); 246 } 247 248 // If we were called with a replacer function, then call the replacer to 249 // obtain a replacement value. 250 251 if (typeof rep === 'function') { 252 value = rep.call(holder, key, value); 253 } 254 255 // What happens next depends on the value's type. 256 257 switch (typeof value) { 258 case 'string': 259 return quote(value); 260 261 case 'number': 262 263 // JSON numbers must be finite. Encode non-finite numbers as null. 264 265 return isFinite(value) ? String(value) : 'null'; 266 267 case 'boolean': 268 case 'null': 269 270 // If the value is a boolean or null, convert it to a string. Note: 271 // typeof null does not produce 'null'. The case is included here in 272 // the remote chance that this gets fixed someday. 273 274 return String(value); 275 276 // If the type is 'object', we might be dealing with an object or an array or 277 // null. 278 279 case 'object': 280 281 // Due to a specification blunder in ECMAScript, typeof null is 'object', 282 // so watch out for that case. 283 284 if (!value) { 285 return 'null'; 286 } 287 288 // Make an array to hold the partial results of stringifying this object value. 289 290 gap += indent; 291 partial = []; 292 293 // Is the value an array? 294 295 if (Object.prototype.toString.apply(value) === '[object Array]') { 296 297 // The value is an array. Stringify every element. Use null as a placeholder 298 // for non-JSON values. 299 300 length = value.length; 301 for (i = 0; i < length; i += 1) { 302 partial[i] = str(i, value) || 'null'; 303 } 304 305 // Join all of the elements together, separated with commas, and wrap them in 306 // brackets. 307 308 v = partial.length === 0 309 ? '[]' 310 : gap 311 ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' 312 : '[' + partial.join(',') + ']'; 313 gap = mind; 314 return v; 315 } 316 317 // If the replacer is an array, use it to select the members to be stringified. 318 319 if (rep && typeof rep === 'object') { 320 length = rep.length; 321 for (i = 0; i < length; i += 1) { 322 if (typeof rep[i] === 'string') { 323 k = rep[i]; 324 v = str(k, value); 325 if (v) { 326 partial.push(quote(k) + (gap ? ': ' : ':') + v); 327 } 328 } 329 } 330 } else { 331 332 // Otherwise, iterate through all of the keys in the object. 333 334 for (k in value) { 335 if (Object.prototype.hasOwnProperty.call(value, k)) { 336 v = str(k, value); 337 if (v) { 338 partial.push(quote(k) + (gap ? ': ' : ':') + v); 339 } 340 } 341 } 342 } 343 344 // Join all of the member texts together, separated with commas, 345 // and wrap them in braces. 346 347 v = partial.length === 0 348 ? '{}' 349 : gap 350 ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' 351 : '{' + partial.join(',') + '}'; 352 gap = mind; 353 return v; 354 } 355 } 356 357 // If the JSON object does not yet have a stringify method, give it one. 358 359 if (typeof JSON.stringify !== 'function') { 360 JSON.stringify = function (value, replacer, space) { 361 362 // The stringify method takes a value and an optional replacer, and an optional 363 // space parameter, and returns a JSON text. The replacer can be a function 364 // that can replace values, or an array of strings that will select the keys. 365 // A default replacer method can be provided. Use of the space parameter can 366 // produce text that is more easily readable. 367 368 var i; 369 gap = ''; 370 indent = ''; 371 372 // If the space parameter is a number, make an indent string containing that 373 // many spaces. 374 375 if (typeof space === 'number') { 376 for (i = 0; i < space; i += 1) { 377 indent += ' '; 378 } 379 380 // If the space parameter is a string, it will be used as the indent string. 381 382 } else if (typeof space === 'string') { 383 indent = space; 384 } 385 386 // If there is a replacer, it must be a function or an array. 387 // Otherwise, throw an error. 388 389 rep = replacer; 390 if (replacer && typeof replacer !== 'function' && 391 (typeof replacer !== 'object' || 392 typeof replacer.length !== 'number')) { 393 throw new Error('JSON.stringify'); 394 } 395 396 // Make a fake root object containing our value under the key of ''. 397 // Return the result of stringifying the value. 398 399 return str('', {'': value}); 400 }; 401 } 402 403 404 // If the JSON object does not yet have a parse method, give it one. 405 406 if (typeof JSON.parse !== 'function') { 407 JSON.parse = function (text, reviver) { 408 409 // The parse method takes a text and an optional reviver function, and returns 410 // a JavaScript value if the text is a valid JSON text. 411 412 var j; 413 414 function walk(holder, key) { 415 416 // The walk method is used to recursively walk the resulting structure so 417 // that modifications can be made. 418 419 var k, v, value = holder[key]; 420 if (value && typeof value === 'object') { 421 for (k in value) { 422 if (Object.prototype.hasOwnProperty.call(value, k)) { 423 v = walk(value, k); 424 if (v !== undefined) { 425 value[k] = v; 426 } else { 427 delete value[k]; 428 } 429 } 430 } 431 } 432 return reviver.call(holder, key, value); 433 } 434 435 436 // Parsing happens in four stages. In the first stage, we replace certain 437 // Unicode characters with escape sequences. JavaScript handles many characters 438 // incorrectly, either silently deleting them, or treating them as line endings. 439 440 text = String(text); 441 cx.lastIndex = 0; 442 if (cx.test(text)) { 443 text = text.replace(cx, function (a) { 444 return '\\u' + 445 ('0000' + a.charCodeAt(0).toString(16)).slice(-4); 446 }); 447 } 448 449 // In the second stage, we run the text against regular expressions that look 450 // for non-JSON patterns. We are especially concerned with '()' and 'new' 451 // because they can cause invocation, and '=' because it can cause mutation. 452 // But just to be safe, we want to reject all unexpected forms. 453 454 // We split the second stage into 4 regexp operations in order to work around 455 // crippling inefficiencies in IE's and Safari's regexp engines. First we 456 // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we 457 // replace all simple value tokens with ']' characters. Third, we delete all 458 // open brackets that follow a colon or comma or that begin the text. Finally, 459 // we look to see that the remaining characters are only whitespace or ']' or 460 // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. 461 462 if (/^[\],:{}\s]*$/ 463 .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') 464 .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') 465 .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { 466 467 // In the third stage we use the eval function to compile the text into a 468 // JavaScript structure. The '{' operator is subject to a syntactic ambiguity 469 // in JavaScript: it can begin a block or an object literal. We wrap the text 470 // in parens to eliminate the ambiguity. 471 472 j = eval('(' + text + ')'); 473 474 // In the optional fourth stage, we recursively walk the new structure, passing 475 // each name/value pair to a reviver function for possible transformation. 476 477 return typeof reviver === 'function' 478 ? walk({'': j}, '') 479 : j; 480 } 481 482 // If the text is not JSON parseable, then a SyntaxError is thrown. 483 484 throw new SyntaxError('JSON.parse'); 485 }; 486 } 487 }()); 488