# 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 at6//7//      http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// 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 and13// limitations under the License.1415/**16 * @fileoverview JSON utility functions.17 * @author arv@google.com (Erik Arvidsson)18 */192021goog.provide('goog.json');22goog.provide('goog.json.Replacer');23goog.provide('goog.json.Reviver');24goog.provide('goog.json.Serializer');252627/**28 * @define {boolean} If true, use the native JSON parsing API.29 * NOTE(user): EXPERIMENTAL, handle with care.  Setting this to true might30 * break your code.  The default {@code goog.json.parse} implementation is able31 * to handle invalid JSON, such as JSPB.32 */33goog.define('goog.json.USE_NATIVE_JSON', false);343536/**37 * Tests if a string is an invalid JSON string. This only ensures that we are38 * not using any invalid characters39 * @param {string} s The string to test.40 * @return {boolean} True if the input is a valid JSON string.41 */42goog.json.isValid = function(s) {43  // All empty whitespace is not valid.44  if (/^\s*$/.test(s)) {45    return false;46  }4748  // This is taken from http://www.json.org/json2.js which is released to the49  // public domain.50  // Changes: We dissallow \u2028 Line separator and \u2029 Paragraph separator51  // inside strings.  We also treat \u2028 and \u2029 as whitespace which they52  // are in the RFC but IE and Safari does not match \s to these so we need to53  // include them in the reg exps in all places where whitespace is allowed.54  // We allowed \x7f inside strings because some tools don't escape it,55  // e.g. http://www.json.org/java/org/json/JSONObject.java5657  // Parsing happens in three stages. In the first stage, we run the text58  // against regular expressions that look for non-JSON patterns. We are59  // especially concerned with '()' and 'new' because they can cause invocation,60  // and '=' because it can cause mutation. But just to be safe, we want to61  // reject all unexpected forms.6263  // We split the first stage into 4 regexp operations in order to work around64  // crippling inefficiencies in IE's and Safari's regexp engines. First we65  // replace all backslash pairs with '@' (a non-JSON character). Second, we66  // replace all simple value tokens with ']' characters. Third, we delete all67  // open brackets that follow a colon or comma or that begin the text. Finally,68  // we look to see that the remaining characters are only whitespace or ']' or69  // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.7071  // Don't make these static since they have the global flag.72  var backslashesRe = /\\["\\\/bfnrtu]/g;73  var simpleValuesRe =74      /"[^"\\\n\r\u2028\u2029\x00-\x08\x0a-\x1f]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;75  var openBracketsRe = /(?:^|:|,)(?:[\s\u2028\u2029]*\[)+/g;76  var remainderRe = /^[\],:{}\s\u2028\u2029]*$/;7778  return remainderRe.test(s.replace(backslashesRe, '@').79      replace(simpleValuesRe, ']').80      replace(openBracketsRe, ''));81};828384/**85 * Parses a JSON string and returns the result. This throws an exception if86 * the string is an invalid JSON string.87 *88 * Note that this is very slow on large strings. If you trust the source of89 * the string then you should use unsafeParse instead.90 *91 * @param {*} s The JSON string to parse.92 * @throws Error if s is invalid JSON.93 * @return {Object} The object generated from the JSON string, or null.94 */95goog.json.parse = goog.json.USE_NATIVE_JSON ?96    /** @type {function(*):Object} */ (goog.global['JSON']['parse']) :97    function(s) {98      var o = String(s);99      if (goog.json.isValid(o)) {100        /** @preserveTry */101        try {102          return /** @type {Object} */ (eval('(' + o + ')'));103        } catch (ex) {104        }105      }106      throw Error('Invalid JSON string: ' + o);107    };108109110/**111 * Parses a JSON string and returns the result. This uses eval so it is open112 * to security issues and it should only be used if you trust the source.113 *114 * @param {string} s The JSON string to parse.115 * @return {Object} The object generated from the JSON string.116 */117goog.json.unsafeParse = goog.json.USE_NATIVE_JSON ?118    /** @type {function(string):Object} */ (goog.global['JSON']['parse']) :119    function(s) {120      return /** @type {Object} */ (eval('(' + s + ')'));121    };122123124/**125 * JSON replacer, as defined in Section 15.12.3 of the ES5 spec.126 * @see http://ecma-international.org/ecma-262/5.1/#sec-15.12.3127 *128 * TODO(nicksantos): Array should also be a valid replacer.129 *130 * @typedef {function(this:Object, string, *): *}131 */132goog.json.Replacer;133134135/**136 * JSON reviver, as defined in Section 15.12.2 of the ES5 spec.137 * @see http://ecma-international.org/ecma-262/5.1/#sec-15.12.3138 *139 * @typedef {function(this:Object, string, *): *}140 */141goog.json.Reviver;142143144/**145 * Serializes an object or a value to a JSON string.146 *147 * @param {*} object The object to serialize.148 * @param {?goog.json.Replacer=} opt_replacer A replacer function149 *     called for each (key, value) pair that determines how the value150 *     should be serialized. By defult, this just returns the value151 *     and allows default serialization to kick in.152 * @throws Error if there are loops in the object graph.153 * @return {string} A JSON string representation of the input.154 */155goog.json.serialize = goog.json.USE_NATIVE_JSON ?156    /** @type {function(*, ?goog.json.Replacer=):string} */157    (goog.global['JSON']['stringify']) :158    function(object, opt_replacer) {159      // NOTE(nicksantos): Currently, we never use JSON.stringify.160      //161      // The last time I evaluated this, JSON.stringify had subtle bugs and162      // behavior differences on all browsers, and the performance win was not163      // large enough to justify all the issues. This may change in the future164      // as browser implementations get better.165      //166      // assertSerialize in json_test contains if branches for the cases167      // that fail.168      return new goog.json.Serializer(opt_replacer).serialize(object);169    };170171172173/**174 * Class that is used to serialize JSON objects to a string.175 * @param {?goog.json.Replacer=} opt_replacer Replacer.176 * @constructor177 */178goog.json.Serializer = function(opt_replacer) {179  /**180   * @type {goog.json.Replacer|null|undefined}181   * @private182   */183  this.replacer_ = opt_replacer;184};185186187/**188 * Serializes an object or a value to a JSON string.189 *190 * @param {*} object The object to serialize.191 * @throws Error if there are loops in the object graph.192 * @return {string} A JSON string representation of the input.193 */194goog.json.Serializer.prototype.serialize = function(object) {195  var sb = [];196  this.serializeInternal(object, sb);197  return sb.join('');198};199200201/**202 * Serializes a generic value to a JSON string203 * @protected204 * @param {*} object The object to serialize.205 * @param {Array} sb Array used as a string builder.206 * @throws Error if there are loops in the object graph.207 */208goog.json.Serializer.prototype.serializeInternal = function(object, sb) {209  switch (typeof object) {210    case 'string':211      this.serializeString_(/** @type {string} */ (object), sb);212      break;213    case 'number':214      this.serializeNumber_(/** @type {number} */ (object), sb);215      break;216    case 'boolean':217      sb.push(object);218      break;219    case 'undefined':220      sb.push('null');221      break;222    case 'object':223      if (object == null) {224        sb.push('null');225        break;226      }227      if (goog.isArray(object)) {228        this.serializeArray(/** @type {!Array} */ (object), sb);229        break;230      }231      // should we allow new String, new Number and new Boolean to be treated232      // as string, number and boolean? Most implementations do not and the233      // need is not very big234      this.serializeObject_(/** @type {Object} */ (object), sb);235      break;236    case 'function':237      // Skip functions.238      // TODO(user) Should we return something here?239      break;240    default:241      throw Error('Unknown type: ' + typeof object);242  }243};244245246/**247 * Character mappings used internally for goog.string.quote248 * @private249 * @type {!Object}250 */251goog.json.Serializer.charToJsonCharCache_ = {252  '\"': '\\"',253  '\\': '\\\\',254  '/': '\\/',255  '\b': '\\b',256  '\f': '\\f',257  '\n': '\\n',258  '\r': '\\r',259  '\t': '\\t',260261  '\x0B': '\\u000b' // '\v' is not supported in JScript262};263264265/**266 * Regular expression used to match characters that need to be replaced.267 * The S60 browser has a bug where unicode characters are not matched by268 * regular expressions. The condition below detects such behaviour and269 * adjusts the regular expression accordingly.270 * @private271 * @type {!RegExp}272 */273goog.json.Serializer.charsToReplace_ = /\uffff/.test('\uffff') ?274    /[\\\"\x00-\x1f\x7f-\uffff]/g : /[\\\"\x00-\x1f\x7f-\xff]/g;275276277/**278 * Serializes a string to a JSON string279 * @private280 * @param {string} s The string to serialize.281 * @param {Array} sb Array used as a string builder.282 */283goog.json.Serializer.prototype.serializeString_ = function(s, sb) {284  // The official JSON implementation does not work with international285  // characters.286  sb.push('"', s.replace(goog.json.Serializer.charsToReplace_, function(c) {287    // caching the result improves performance by a factor 2-3288    if (c in goog.json.Serializer.charToJsonCharCache_) {289      return goog.json.Serializer.charToJsonCharCache_[c];290    }291292    var cc = c.charCodeAt(0);293    var rv = '\\u';294    if (cc < 16) {295      rv += '000';296    } else if (cc < 256) {297      rv += '00';298    } else if (cc < 4096) { // \u1000299      rv += '0';300    }301    return goog.json.Serializer.charToJsonCharCache_[c] = rv + cc.toString(16);302  }), '"');303};304305306/**307 * Serializes a number to a JSON string308 * @private309 * @param {number} n The number to serialize.310 * @param {Array} sb Array used as a string builder.311 */312goog.json.Serializer.prototype.serializeNumber_ = function(n, sb) {313  sb.push(isFinite(n) && !isNaN(n) ? n : 'null');314};315316317/**318 * Serializes an array to a JSON string319 * @param {Array} arr The array to serialize.320 * @param {Array} sb Array used as a string builder.321 * @protected322 */323goog.json.Serializer.prototype.serializeArray = function(arr, sb) {324  var l = arr.length;325  sb.push('[');326  var sep = '';327  for (var i = 0; i < l; i++) {328    sb.push(sep);329330    var value = arr[i];331    this.serializeInternal(332        this.replacer_ ? this.replacer_.call(arr, String(i), value) : value,333        sb);334335    sep = ',';336  }337  sb.push(']');338};339340341/**342 * Serializes an object to a JSON string343 * @private344 * @param {Object} obj The object to serialize.345 * @param {Array} sb Array used as a string builder.346 */347goog.json.Serializer.prototype.serializeObject_ = function(obj, sb) {348  sb.push('{');349  var sep = '';350  for (var key in obj) {351    if (Object.prototype.hasOwnProperty.call(obj, key)) {352      var value = obj[key];353      // Skip functions.354      // TODO(ptucker) Should we return something for function properties?355      if (typeof value != 'function') {356        sb.push(sep);357        this.serializeString_(key, sb);358        sb.push(':');359360        this.serializeInternal(361            this.replacer_ ? this.replacer_.call(obj, key, value) : value,362            sb);363364        sep = ',';365      }366    }367  }368  sb.push('}');369};