2 2010-11-01 Chris Leonello
4 Slightly modified version of the original json2.js to put JSON
5 functions under the $.jqplot namespace.
7 licensing and orignal comments follow:
9 http://www.JSON.org/json2.js
14 NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
16 See http://www.JSON.org/js.html
19 This code should be minified before deployment.
20 See http://javascript.crockford.com/jsmin.html
22 USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
26 This file creates a global JSON object containing two methods: stringify
29 $.jqplot.JSON.stringify(value, replacer, space)
30 value any JavaScript value, usually an object or array.
32 replacer an optional parameter that determines how object
33 values are stringified for objects. It can be a
34 function or an array of strings.
36 space an optional parameter that specifies the indentation
37 of nested structures. If it is omitted, the text will
38 be packed without extra whitespace. If it is a number,
39 it will specify the number of spaces to indent at each
40 level. If it is a string (such as '\t' or ' '),
41 it contains the characters used to indent at each level.
43 This method produces a JSON text from a JavaScript value.
45 When an object value is found, if the object contains a toJSON
46 method, its toJSON method will be called and the result will be
47 stringified. A toJSON method does not serialize: it returns the
48 value represented by the name/value pair that should be serialized,
49 or undefined if nothing should be serialized. The toJSON method
50 will be passed the key associated with the value, and this will be
53 For example, this would serialize Dates as ISO strings.
55 Date.prototype.toJSON = function (key) {
57 // Format integers to have at least two digits.
58 return n < 10 ? '0' + n : n;
61 return this.getUTCFullYear() + '-' +
62 f(this.getUTCMonth() + 1) + '-' +
63 f(this.getUTCDate()) + 'T' +
64 f(this.getUTCHours()) + ':' +
65 f(this.getUTCMinutes()) + ':' +
66 f(this.getUTCSeconds()) + 'Z';
69 You can provide an optional replacer method. It will be passed the
70 key and value of each member, with this bound to the containing
71 object. The value that is returned from your method will be
72 serialized. If your method returns undefined, then the member will
73 be excluded from the serialization.
75 If the replacer parameter is an array of strings, then it will be
76 used to select the members to be serialized. It filters the results
77 such that only members with keys listed in the replacer array are
80 Values that do not have JSON representations, such as undefined or
81 functions, will not be serialized. Such values in objects will be
82 dropped; in arrays they will be replaced with null. You can use
83 a replacer function to replace those with JSON values.
84 $.jqplot.JSON.stringify(undefined) returns undefined.
86 The optional space parameter produces a stringification of the
87 value that is filled with line breaks and indentation to make it
90 If the space parameter is a non-empty string, then that string will
91 be used for indentation. If the space parameter is a number, then
92 the indentation will be that many spaces.
96 text = $.jqplot.JSON.stringify(['e', {pluribus: 'unum'}]);
97 // text is '["e",{"pluribus":"unum"}]'
100 text = $.jqplot.JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
101 // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
103 text = $.jqplot.JSON.stringify([new Date()], function (key, value) {
104 return this[key] instanceof Date ?
105 'Date(' + this[key] + ')' : value;
107 // text is '["Date(---current time---)"]'
110 $.jqplot.JSON.parse(text, reviver)
111 This method parses a JSON text to produce an object or array.
112 It can throw a SyntaxError exception.
114 The optional reviver parameter is a function that can filter and
115 transform the results. It receives each of the keys and values,
116 and its return value is used instead of the original value.
117 If it returns what it received, then the structure is not modified.
118 If it returns undefined then the member is deleted.
122 // Parse the text. Values that look like ISO date strings will
123 // be converted to Date objects.
125 myData = $.jqplot.JSON.parse(text, function (key, value) {
127 if (typeof value === 'string') {
129 /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
131 return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
138 myData = $.jqplot.JSON.parse('["Date(09/09/2001)"]', function (key, value) {
140 if (typeof value === 'string' &&
141 value.slice(0, 5) === 'Date(' &&
142 value.slice(-1) === ')') {
143 d = new Date(value.slice(5, -1));
152 This is a reference implementation. You are free to copy, modify, or
158 $.jqplot.JSON = window.JSON;
165 // Format integers to have at least two digits.
166 return n < 10 ? '0' + n : n;
169 if (typeof Date.prototype.toJSON !== 'function') {
171 Date.prototype.toJSON = function (key) {
173 return isFinite(this.valueOf()) ?
174 this.getUTCFullYear() + '-' +
175 f(this.getUTCMonth() + 1) + '-' +
176 f(this.getUTCDate()) + 'T' +
177 f(this.getUTCHours()) + ':' +
178 f(this.getUTCMinutes()) + ':' +
179 f(this.getUTCSeconds()) + 'Z' : null;
182 String.prototype.toJSON =
183 Number.prototype.toJSON =
184 Boolean.prototype.toJSON = function (key) {
185 return this.valueOf();
189 var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
190 escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
193 meta = { // table of character substitutions
205 function quote(string) {
207 // If the string contains no control characters, no quote characters, and no
208 // backslash characters, then we can safely slap some quotes around it.
209 // Otherwise we must also replace the offending characters with safe escape
212 escapable.lastIndex = 0;
213 return escapable.test(string) ?
214 '"' + string.replace(escapable, function (a) {
216 return typeof c === 'string' ? c :
217 '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
223 function str(key, holder) {
225 // Produce a string from holder[key].
227 var i, // The loop counter.
228 k, // The member key.
229 v, // The member value.
235 // If the value has a toJSON method, call it to obtain a replacement value.
237 if (value && typeof value === 'object' &&
238 typeof value.toJSON === 'function') {
239 value = value.toJSON(key);
242 // If we were called with a replacer function, then call the replacer to
243 // obtain a replacement value.
245 if (typeof rep === 'function') {
246 value = rep.call(holder, key, value);
249 // What happens next depends on the value's type.
251 switch (typeof value) {
257 // JSON numbers must be finite. Encode non-finite numbers as null.
259 return isFinite(value) ? String(value) : 'null';
264 // If the value is a boolean or null, convert it to a string. Note:
265 // typeof null does not produce 'null'. The case is included here in
266 // the remote chance that this gets fixed someday.
268 return String(value);
270 // If the type is 'object', we might be dealing with an object or an array or
275 // Due to a specification blunder in ECMAScript, typeof null is 'object',
276 // so watch out for that case.
282 // Make an array to hold the partial results of stringifying this object value.
287 // Is the value an array?
289 if (Object.prototype.toString.apply(value) === '[object Array]') {
291 // The value is an array. Stringify every element. Use null as a placeholder
292 // for non-JSON values.
294 length = value.length;
295 for (i = 0; i < length; i += 1) {
296 partial[i] = str(i, value) || 'null';
299 // Join all of the elements together, separated with commas, and wrap them in
302 v = partial.length === 0 ? '[]' :
304 partial.join(',\n' + gap) + '\n' +
306 '[' + partial.join(',') + ']';
311 // If the replacer is an array, use it to select the members to be stringified.
313 if (rep && typeof rep === 'object') {
315 for (i = 0; i < length; i += 1) {
317 if (typeof k === 'string') {
320 partial.push(quote(k) + (gap ? ': ' : ':') + v);
326 // Otherwise, iterate through all of the keys in the object.
329 if (Object.hasOwnProperty.call(value, k)) {
332 partial.push(quote(k) + (gap ? ': ' : ':') + v);
338 // Join all of the member texts together, separated with commas,
339 // and wrap them in braces.
341 v = partial.length === 0 ? '{}' :
342 gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
343 mind + '}' : '{' + partial.join(',') + '}';
349 // If the JSON object does not yet have a stringify method, give it one.
351 if (typeof $.jqplot.JSON.stringify !== 'function') {
352 $.jqplot.JSON.stringify = function (value, replacer, space) {
354 // The stringify method takes a value and an optional replacer, and an optional
355 // space parameter, and returns a JSON text. The replacer can be a function
356 // that can replace values, or an array of strings that will select the keys.
357 // A default replacer method can be provided. Use of the space parameter can
358 // produce text that is more easily readable.
364 // If the space parameter is a number, make an indent string containing that
367 if (typeof space === 'number') {
368 for (i = 0; i < space; i += 1) {
372 // If the space parameter is a string, it will be used as the indent string.
374 } else if (typeof space === 'string') {
378 // If there is a replacer, it must be a function or an array.
379 // Otherwise, throw an error.
382 if (replacer && typeof replacer !== 'function' &&
383 (typeof replacer !== 'object' ||
384 typeof replacer.length !== 'number')) {
385 throw new Error('$.jqplot.JSON.stringify');
388 // Make a fake root object containing our value under the key of ''.
389 // Return the result of stringifying the value.
391 return str('', {'': value});
396 // If the JSON object does not yet have a parse method, give it one.
398 if (typeof $.jqplot.JSON.parse !== 'function') {
399 $.jqplot.JSON.parse = function (text, reviver) {
401 // The parse method takes a text and an optional reviver function, and returns
402 // a JavaScript value if the text is a valid JSON text.
406 function walk(holder, key) {
408 // The walk method is used to recursively walk the resulting structure so
409 // that modifications can be made.
411 var k, v, value = holder[key];
412 if (value && typeof value === 'object') {
414 if (Object.hasOwnProperty.call(value, k)) {
416 if (v !== undefined) {
424 return reviver.call(holder, key, value);
428 // Parsing happens in four stages. In the first stage, we replace certain
429 // Unicode characters with escape sequences. JavaScript handles many characters
430 // incorrectly, either silently deleting them, or treating them as line endings.
435 text = text.replace(cx, function (a) {
437 ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
441 // In the second stage, we run the text against regular expressions that look
442 // for non-JSON patterns. We are especially concerned with '()' and 'new'
443 // because they can cause invocation, and '=' because it can cause mutation.
444 // But just to be safe, we want to reject all unexpected forms.
446 // We split the second stage into 4 regexp operations in order to work around
447 // crippling inefficiencies in IE's and Safari's regexp engines. First we
448 // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
449 // replace all simple value tokens with ']' characters. Third, we delete all
450 // open brackets that follow a colon or comma or that begin the text. Finally,
451 // we look to see that the remaining characters are only whitespace or ']' or
452 // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
454 if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
456 // In the third stage we use the eval function to compile the text into a
457 // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
458 // in JavaScript: it can begin a block or an object literal. We wrap the text
459 // in parens to eliminate the ambiguity.
461 j = eval('(' + text + ')');
463 // In the optional fourth stage, we recursively walk the new structure, passing
464 // each name/value pair to a reviver function for possible transformation.
466 return typeof reviver === 'function' ?
467 walk({'': j}, '') : j;
470 // If the text is not JSON parseable, then a SyntaxError is thrown.
472 throw new SyntaxError('$.jqplot.JSON.parse');