add 'next actions'; sync to json server
[hyena.git] / app / ext / json2.js
blob31b1fd7054621e030ea7ae153086b9cb7698f8db
1 /*
2     json2.js
3     2007-12-02
5     Public Domain
7     No warranty expressed or implied. Use at your own risk.
9     See http://www.JSON.org/js.html
11     This file creates a global JSON object containing two methods:
13         JSON.stringify(value, whitelist)
14             value       any JavaScript value, usually an object or array.
16             whitelist   an optional array prameter that determines how object
17                         values are stringified.
19             This method produces a JSON text from a JavaScript value.
20             There are three possible ways to stringify an object, depending
21             on the optional whitelist parameter.
23             If an object has a toJSON method, then the toJSON() method will be
24             called. The value returned from the toJSON method will be
25             stringified.
27             Otherwise, if the optional whitelist parameter is an array, then
28             the elements of the array will be used to select members of the
29             object for stringification.
31             Otherwise, if there is no whitelist parameter, then all of the
32             members of the object will be stringified.
34             Values that do not have JSON representaions, such as undefined or
35             functions, will not be serialized. Such values in objects will be
36             dropped; in arrays will be replaced with null.
37             JSON.stringify(undefined) returns undefined. Dates will be
38             stringified as quoted ISO dates.
40             Example:
42             var text = JSON.stringify(['e', {pluribus: 'unum'}]);
43             // text is '["e",{"pluribus":"unum"}]'
45         JSON.parse(text, filter)
46             This method parses a JSON text to produce an object or
47             array. It can throw a SyntaxError exception.
49             The optional filter parameter is a function that can filter and
50             transform the results. It receives each of the keys and values, and
51             its return value is used instead of the original value. If it
52             returns what it received, then structure is not modified. If it
53             returns undefined then the member is deleted.
55             Example:
57             // Parse the text. If a key contains the string 'date' then
58             // convert the value to a date.
60             myData = JSON.parse(text, function (key, value) {
61                 return key.indexOf('date') >= 0 ? new Date(value) : value;
62             });
64     This is a reference implementation. You are free to copy, modify, or
65     redistribute.
67     Use your own copy. It is extremely unwise to load third party
68     code into your pages.
71 /*jslint evil: true */
73 /*global JSON */
75 /*members "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
76     charCodeAt, floor, getUTCDate, getUTCFullYear, getUTCHours,
77     getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, length,
78     parse, propertyIsEnumerable, prototype, push, replace, stringify, test,
79     toJSON, toString
82 if (!this.JSON) {
84     JSON = function () {
86         function f(n) {    // Format integers to have at least two digits.
87             return n < 10 ? '0' + n : n;
88         }
90         Date.prototype.toJSON = function () {
92 // Eventually, this method will be based on the date.toISOString method.
94             return this.getUTCFullYear()   + '-' +
95                  f(this.getUTCMonth() + 1) + '-' +
96                  f(this.getUTCDate())      + 'T' +
97                  f(this.getUTCHours())     + ':' +
98                  f(this.getUTCMinutes())   + ':' +
99                  f(this.getUTCSeconds())   + 'Z';
100         };
103         var m = {    // table of character substitutions
104             '\b': '\\b',
105             '\t': '\\t',
106             '\n': '\\n',
107             '\f': '\\f',
108             '\r': '\\r',
109             '"' : '\\"',
110             '\\': '\\\\'
111         };
113         function stringify(value, whitelist) {
114             var a,          // The array holding the partial texts.
115                 i,          // The loop counter.
116                 k,          // The member key.
117                 l,          // Length.
118                 r = /["\\\x00-\x1f\x7f-\x9f]/g,
119                 v;          // The member value.
121             switch (typeof value) {
122             case 'string':
124 // If the string contains no control characters, no quote characters, and no
125 // backslash characters, then we can safely slap some quotes around it.
126 // Otherwise we must also replace the offending characters with safe sequences.
128                 return r.test(value) ?
129                     '"' + value.replace(r, function (a) {
130                         var c = m[a];
131                         if (c) {
132                             return c;
133                         }
134                         c = a.charCodeAt();
135                         return '\\u00' + Math.floor(c / 16).toString(16) +
136                                                    (c % 16).toString(16);
137                     }) + '"' :
138                     '"' + value + '"';
140             case 'number':
142 // JSON numbers must be finite. Encode non-finite numbers as null.
144                 return isFinite(value) ? String(value) : 'null';
146             case 'boolean':
147             case 'null':
148                 return String(value);
150             case 'object':
152 // Due to a specification blunder in ECMAScript,
153 // typeof null is 'object', so watch out for that case.
155                 if (!value) {
156                     return 'null';
157                 }
159 // If the object has a toJSON method, call it, and stringify the result.
161                 if (typeof value.toJSON === 'function') {
162                     return stringify(value.toJSON());
163                 }
164                 a = [];
165                 if (typeof value.length === 'number' &&
166                         !(value.propertyIsEnumerable('length'))) {
168 // The object is an array. Stringify every element. Use null as a placeholder
169 // for non-JSON values.
171                     l = value.length;
172                     for (i = 0; i < l; i += 1) {
173                         a.push(stringify(value[i], whitelist) || 'null');
174                     }
176 // Join all of the elements together and wrap them in brackets.
178                     return '[' + a.join(',') + ']';
179                 }
180                 if (whitelist) {
182 // If a whitelist (array of keys) is provided, use it to select the components
183 // of the object.
185                     l = whitelist.length;
186                     for (i = 0; i < l; i += 1) {
187                         k = whitelist[i];
188                         if (typeof k === 'string') {
189                             v = stringify(value[k], whitelist);
190                             if (v) {
191                                 a.push(stringify(k) + ':' + v);
192                             }
193                         }
194                     }
195                 } else {
197 // Otherwise, iterate through all of the keys in the object.
199                     for (k in value) {
200                         if (typeof k === 'string') {
201                             v = stringify(value[k], whitelist);
202                             if (v) {
203                                 a.push(stringify(k) + ':' + v);
204                             }
205                         }
206                     }
207                 }
209 // Join all of the member texts together and wrap them in braces.
211                 return '{' + a.join(',') + '}';
212             }
213         }
215         return {
216             stringify: stringify,
217             parse: function (text, filter) {
218                 var j;
220                 function walk(k, v) {
221                     var i, n;
222                     if (v && typeof v === 'object') {
223                         for (i in v) {
224                             if (Object.prototype.hasOwnProperty.apply(v, [i])) {
225                                 n = walk(i, v[i]);
226                                 if (n !== undefined) {
227                                     v[i] = n;
228                                 }
229                             }
230                         }
231                     }
232                     return filter(k, v);
233                 }
236 // Parsing happens in three stages. In the first stage, we run the text against
237 // regular expressions that look for non-JSON patterns. We are especially
238 // concerned with '()' and 'new' because they can cause invocation, and '='
239 // because it can cause mutation. But just to be safe, we want to reject all
240 // unexpected forms.
242 // We split the first stage into 4 regexp operations in order to work around
243 // crippling inefficiencies in IE's and Safari's regexp engines. First we
244 // replace all backslash pairs with '@' (a non-JSON character). Second, we
245 // replace all simple value tokens with ']' characters. Third, we delete all
246 // open brackets that follow a colon or comma or that begin the text. Finally,
247 // we look to see that the remaining characters are only whitespace or ']' or
248 // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
250                 if (/^[\],:{}\s]*$/.test(text.replace(/\\./g, '@').
251 replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(:?[eE][+\-]?\d+)?/g, ']').
252 replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
254 // In the second stage we use the eval function to compile the text into a
255 // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
256 // in JavaScript: it can begin a block or an object literal. We wrap the text
257 // in parens to eliminate the ambiguity.
259                     j = eval('(' + text + ')');
261 // In the optional third stage, we recursively walk the new structure, passing
262 // each name/value pair to a filter function for possible transformation.
264                     return typeof filter === 'function' ? walk('', j) : j;
265                 }
267 // If the text is not JSON parseable, then a SyntaxError is thrown.
269                 throw new SyntaxError('parseJSON');
270             }
271         };
272     }();