lib/goog/json/json.js

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