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