Debian Codegraph @

closure-library/closure/goog/json/json.js

raw
1 // Copyright 2006 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview JSON utility functions.
17 * @author [email protected] (Erik Arvidsson)
18 */
19
20
21 goog.provide('goog.json');
22 goog.provide('goog.json.Replacer');
23 goog.provide('goog.json.Reviver');
24 goog.provide('goog.json.Serializer');
25
26
27 /**
28 * @define {boolean} If true, use the native JSON parsing API.
29 * NOTE: The default {@code goog.json.parse} implementation is able to handle
30 * invalid JSON. JSPB used to produce invalid JSON which is not the case
31 * anymore so this is safe to enable for parsing JSPB. Using native JSON is
32 * faster and safer than the default implementation using {@code eval}.
33 */
34 goog.define('goog.json.USE_NATIVE_JSON', false);
35
36 /**
37 * @define {boolean} If true, try the native JSON parsing API first. If it
38 * fails, log an error and use {@code eval} instead. This is useful when
39 * transitioning to {@code goog.json.USE_NATIVE_JSON}. The error logger needs to
40 * be set by {@code goog.json.setErrorLogger}. If it is not set then the error
41 * is ignored.
42 */
43 goog.define('goog.json.TRY_NATIVE_JSON', false);
44
45
46 /**
47 * Tests if a string is an invalid JSON string. This only ensures that we are
48 * not using any invalid characters
49 * @param {string} s The string to test.
50 * @return {boolean} True if the input is a valid JSON string.
51 */
52 goog.json.isValid = function(s) {
53 // All empty whitespace is not valid.
54 if (/^\s*$/.test(s)) {
55 return false;
56 }
57
58 // This is taken from http://www.json.org/json2.js which is released to the
59 // public domain.
60 // Changes: We dissallow \u2028 Line separator and \u2029 Paragraph separator
61 // inside strings. We also treat \u2028 and \u2029 as whitespace which they
62 // are in the RFC but IE and Safari does not match \s to these so we need to
63 // include them in the reg exps in all places where whitespace is allowed.
64 // We allowed \x7f inside strings because some tools don't escape it,
65 // e.g. http://www.json.org/java/org/json/JSONObject.java
66
67 // Parsing happens in three stages. In the first stage, we run the text
68 // against regular expressions that look for non-JSON patterns. We are
69 // especially concerned with '()' and 'new' because they can cause invocation,
70 // and '=' because it can cause mutation. But just to be safe, we want to
71 // reject all unexpected forms.
72
73 // We split the first stage into 4 regexp operations in order to work around
74 // crippling inefficiencies in IE's and Safari's regexp engines. First we
75 // replace all backslash pairs with '@' (a non-JSON character). Second, we
76 // replace all simple value tokens with ']' characters, but only when followed
77 // by a colon, comma, closing bracket or end of string. Third, we delete all
78 // open brackets that follow a colon or comma or that begin the text. Finally,
79 // we look to see that the remaining characters are only whitespace or ']' or
80 // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
81
82 // Don't make these static since they have the global flag.
83 var backslashesRe = /\\["\\\/bfnrtu]/g;
84 var simpleValuesRe =
85 /(?:"[^"\\\n\r\u2028\u2029\x00-\x08\x0a-\x1f]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)[\s\u2028\u2029]*(?=:|,|]|}|$)/g;
86 var openBracketsRe = /(?:^|:|,)(?:[\s\u2028\u2029]*\[)+/g;
87 var remainderRe = /^[\],:{}\s\u2028\u2029]*$/;
88
89 return remainderRe.test(
90 s.replace(backslashesRe, '@')
91 .replace(simpleValuesRe, ']')
92 .replace(openBracketsRe, ''));
93 };
94
95 /**
96 * Logs a parsing error in {@code JSON.parse} solvable by using {@code eval}
97 * if {@code goog.json.TRY_NATIVE_JSON} is enabled.
98 * @private {function(string, !Error)} The first parameter is the error message,
99 * the second is the exception thrown by {@code JSON.parse}.
100 */
101 goog.json.errorLogger_ = goog.nullFunction;
102
103
104 /**
105 * Sets an error logger to use if there's a recoverable parsing error and {@code
106 * goog.json.TRY_NATIVE_JSON} is enabled.
107 * @param {function(string, !Error)} errorLogger The first parameter is the
108 * error message, the second is the exception thrown by {@code JSON.parse}.
109 */
110 goog.json.setErrorLogger = function(errorLogger) {
111 goog.json.errorLogger_ = errorLogger;
112 };
113
114
115 /**
116 * Parses a JSON string and returns the result. This throws an exception if
117 * the string is an invalid JSON string.
118 *
119 * Note that this is very slow on large strings. Use JSON.parse if possible.
120 *
121 * @param {*} s The JSON string to parse.
122 * @throws Error if s is invalid JSON.
123 * @return {Object} The object generated from the JSON string, or null.
124 * @deprecated Use JSON.parse.
125 */
126 goog.json.parse = goog.json.USE_NATIVE_JSON ?
127 /** @type {function(*):Object} */ (goog.global['JSON']['parse']) :
128 function(s) {
129 var error;
130 if (goog.json.TRY_NATIVE_JSON) {
131 try {
132 return goog.global['JSON']['parse'](s);
133 } catch (ex) {
134 error = ex;
135 }
136 }
137 var o = String(s);
138 if (goog.json.isValid(o)) {
139
140 try {
141 var result = /** @type {?Object} */ (eval('(' + o + ')'));
142 if (error) {
143 goog.json.errorLogger_('Invalid JSON: ' + o, error);
144 }
145 return result;
146 } catch (ex) {
147 }
148 }
149 throw new Error('Invalid JSON string: ' + o);
150 };
151
152
153 /**
154 * JSON replacer, as defined in Section 15.12.3 of the ES5 spec.
155 * @see http://ecma-international.org/ecma-262/5.1/#sec-15.12.3
156 *
157 * TODO(nicksantos): Array should also be a valid replacer.
158 *
159 * @typedef {function(this:Object, string, *): *}
160 */
161 goog.json.Replacer;
162
163
164 /**
165 * JSON reviver, as defined in Section 15.12.2 of the ES5 spec.
166 * @see http://ecma-international.org/ecma-262/5.1/#sec-15.12.3
167 *
168 * @typedef {function(this:Object, string, *): *}
169 */
170 goog.json.Reviver;
171
172
173 /**
174 * Serializes an object or a value to a JSON string.
175 *
176 * @param {*} object The object to serialize.
177 * @param {?goog.json.Replacer=} opt_replacer A replacer function
178 * called for each (key, value) pair that determines how the value
179 * should be serialized. By defult, this just returns the value
180 * and allows default serialization to kick in.
181 * @throws Error if there are loops in the object graph.
182 * @return {string} A JSON string representation of the input.
183 */
184 goog.json.serialize = goog.json.USE_NATIVE_JSON ?
185 /** @type {function(*, ?goog.json.Replacer=):string} */
186 (goog.global['JSON']['stringify']) :
187 function(object, opt_replacer) {
188 // NOTE(nicksantos): Currently, we never use JSON.stringify.
189 //
190 // The last time I evaluated this, JSON.stringify had subtle bugs and
191 // behavior differences on all browsers, and the performance win was not
192 // large enough to justify all the issues. This may change in the future
193 // as browser implementations get better.
194 //
195 // assertSerialize in json_test contains if branches for the cases
196 // that fail.
197 return new goog.json.Serializer(opt_replacer).serialize(object);
198 };
199
200
201
202 /**
203 * Class that is used to serialize JSON objects to a string.
204 * @param {?goog.json.Replacer=} opt_replacer Replacer.
205 * @constructor
206 */
207 goog.json.Serializer = function(opt_replacer) {
208 /**
209 * @type {goog.json.Replacer|null|undefined}
210 * @private
211 */
212 this.replacer_ = opt_replacer;
213 };
214
215
216 /**
217 * Serializes an object or a value to a JSON string.
218 *
219 * @param {*} object The object to serialize.
220 * @throws Error if there are loops in the object graph.
221 * @return {string} A JSON string representation of the input.
222 */
223 goog.json.Serializer.prototype.serialize = function(object) {
224 var sb = [];
225 this.serializeInternal(object, sb);
226 return sb.join('');
227 };
228
229
230 /**
231 * Serializes a generic value to a JSON string
232 * @protected
233 * @param {*} object The object to serialize.
234 * @param {Array<string>} sb Array used as a string builder.
235 * @throws Error if there are loops in the object graph.
236 */
237 goog.json.Serializer.prototype.serializeInternal = function(object, sb) {
238 if (object == null) {
239 // undefined == null so this branch covers undefined as well as null
240 sb.push('null');
241 return;
242 }
243
244 if (typeof object == 'object') {
245 if (goog.isArray(object)) {
246 this.serializeArray(object, sb);
247 return;
248 } else if (
249 object instanceof String || object instanceof Number ||
250 object instanceof Boolean) {
251 object = object.valueOf();
252 // Fall through to switch below.
253 } else {
254 this.serializeObject_(/** @type {!Object} */ (object), sb);
255 return;
256 }
257 }
258
259 switch (typeof object) {
260 case 'string':
261 this.serializeString_(object, sb);
262 break;
263 case 'number':
264 this.serializeNumber_(object, sb);
265 break;
266 case 'boolean':
267 sb.push(String(object));
268 break;
269 case 'function':
270 sb.push('null');
271 break;
272 default:
273 throw new Error('Unknown type: ' + typeof object);
274 }
275 };
276
277
278 /**
279 * Character mappings used internally for goog.string.quote
280 * @private
281 * @type {!Object}
282 */
283 goog.json.Serializer.charToJsonCharCache_ = {
284 '\"': '\\"',
285 '\\': '\\\\',
286 '/': '\\/',
287 '\b': '\\b',
288 '\f': '\\f',
289 '\n': '\\n',
290 '\r': '\\r',
291 '\t': '\\t',
292
293 '\x0B': '\\u000b' // '\v' is not supported in JScript
294 };
295
296
297 /**
298 * Regular expression used to match characters that need to be replaced.
299 * The S60 browser has a bug where unicode characters are not matched by
300 * regular expressions. The condition below detects such behaviour and
301 * adjusts the regular expression accordingly.
302 * @private
303 * @type {!RegExp}
304 */
305 goog.json.Serializer.charsToReplace_ = /\uffff/.test('\uffff') ?
306 /[\\\"\x00-\x1f\x7f-\uffff]/g :
307 /[\\\"\x00-\x1f\x7f-\xff]/g;
308
309
310 /**
311 * Serializes a string to a JSON string
312 * @private
313 * @param {string} s The string to serialize.
314 * @param {Array<string>} sb Array used as a string builder.
315 */
316 goog.json.Serializer.prototype.serializeString_ = function(s, sb) {
317 // The official JSON implementation does not work with international
318 // characters.
319 sb.push('"', s.replace(goog.json.Serializer.charsToReplace_, function(c) {
320 // caching the result improves performance by a factor 2-3
321 var rv = goog.json.Serializer.charToJsonCharCache_[c];
322 if (!rv) {
323 rv = '\\u' + (c.charCodeAt(0) | 0x10000).toString(16).substr(1);
324 goog.json.Serializer.charToJsonCharCache_[c] = rv;
325 }
326 return rv;
327 }), '"');
328 };
329
330
331 /**
332 * Serializes a number to a JSON string
333 * @private
334 * @param {number} n The number to serialize.
335 * @param {Array<string>} sb Array used as a string builder.
336 */
337 goog.json.Serializer.prototype.serializeNumber_ = function(n, sb) {
338 sb.push(isFinite(n) && !isNaN(n) ? String(n) : 'null');
339 };
340
341
342 /**
343 * Serializes an array to a JSON string
344 * @param {Array<string>} arr The array to serialize.
345 * @param {Array<string>} sb Array used as a string builder.
346 * @protected
347 */
348 goog.json.Serializer.prototype.serializeArray = function(arr, sb) {
349 var l = arr.length;
350 sb.push('[');
351 var sep = '';
352 for (var i = 0; i < l; i++) {
353 sb.push(sep);
354
355 var value = arr[i];
356 this.serializeInternal(
357 this.replacer_ ? this.replacer_.call(arr, String(i), value) : value,
358 sb);
359
360 sep = ',';
361 }
362 sb.push(']');
363 };
364
365
366 /**
367 * Serializes an object to a JSON string
368 * @private
369 * @param {!Object} obj The object to serialize.
370 * @param {Array<string>} sb Array used as a string builder.
371 */
372 goog.json.Serializer.prototype.serializeObject_ = function(obj, sb) {
373 sb.push('{');
374 var sep = '';
375 for (var key in obj) {
376 if (Object.prototype.hasOwnProperty.call(obj, key)) {
377 var value = obj[key];
378 // Skip functions.
379 if (typeof value != 'function') {
380 sb.push(sep);
381 this.serializeString_(key, sb);
382 sb.push(':');
383
384 this.serializeInternal(
385 this.replacer_ ? this.replacer_.call(obj, key, value) : value, sb);
386
387 sep = ',';
388 }
389 }
390 }
391 sb.push('}');
392 };