# 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 * @private42 */43goog.json.isValid_ = function(s) {44  // All empty whitespace is not valid.45  if (/^\s*$/.test(s)) {46    return false;47  }4849  // This is taken from http://www.json.org/json2.js which is released to the50  // public domain.51  // Changes: We dissallow \u2028 Line separator and \u2029 Paragraph separator52  // inside strings.  We also treat \u2028 and \u2029 as whitespace which they53  // are in the RFC but IE and Safari does not match \s to these so we need to54  // 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.java5758  // Parsing happens in three stages. In the first stage, we run the text59  // against regular expressions that look for non-JSON patterns. We are60  // especially concerned with '()' and 'new' because they can cause invocation,61  // and '=' because it can cause mutation. But just to be safe, we want to62  // reject all unexpected forms.6364  // We split the first stage into 4 regexp operations in order to work around65  // crippling inefficiencies in IE's and Safari's regexp engines. First we66  // replace all backslash pairs with '@' (a non-JSON character). Second, we67  // replace all simple value tokens with ']' characters. Third, we delete all68  // 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 ']' or70  // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.7172  // 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]*$/;7879  return remainderRe.test(s.replace(backslashesRe, '@').80      replace(simpleValuesRe, ']').81      replace(openBracketsRe, ''));82};838485/**86 * Parses a JSON string and returns the result. This throws an exception if87 * the string is an invalid JSON string.88 *89 * Note that this is very slow on large strings. If you trust the source of90 * 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    };109110111/**112 * Parses a JSON string and returns the result. This uses eval so it is open113 * 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    };123124125/**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.3128 *129 * TODO(nicksantos): Array should also be a valid replacer.130 *131 * @typedef {function(this:Object, string, *): *}132 */133goog.json.Replacer;134135136/**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.3139 *140 * @typedef {function(this:Object, string, *): *}141 */142goog.json.Reviver;143144145/**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 function150 *     called for each (key, value) pair that determines how the value151 *     should be serialized. By defult, this just returns the value152 *     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 and163      // behavior differences on all browsers, and the performance win was not164      // large enough to justify all the issues. This may change in the future165      // as browser implementations get better.166      //167      // assertSerialize in json_test contains if branches for the cases168      // that fail.169      return new goog.json.Serializer(opt_replacer).serialize(object);170    };171172173174/**175 * Class that is used to serialize JSON objects to a string.176 * @param {?goog.json.Replacer=} opt_replacer Replacer.177 * @constructor178 */179goog.json.Serializer = function(opt_replacer) {180  /**181   * @type {goog.json.Replacer|null|undefined}182   * @private183   */184  this.replacer_ = opt_replacer;185};186187188/**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};200201202/**203 * Serializes a generic value to a JSON string204 * @protected205 * @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 treated233      // as string, number and boolean? Most implementations do not and the234      // need is not very big235      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};245246247/**248 * Character mappings used internally for goog.string.quote249 * @private250 * @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',261262  '\x0B': '\\u000b' // '\v' is not supported in JScript263};264265266/**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 by269 * regular expressions. The condition below detects such behaviour and270 * adjusts the regular expression accordingly.271 * @private272 * @type {!RegExp}273 */274goog.json.Serializer.charsToReplace_ = /\uffff/.test('\uffff') ?275    /[\\\"\x00-\x1f\x7f-\uffff]/g : /[\\\"\x00-\x1f\x7f-\xff]/g;276277278/**279 * Serializes a string to a JSON string280 * @private281 * @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 international286  // characters.287  sb.push('"', s.replace(goog.json.Serializer.charsToReplace_, function(c) {288    // caching the result improves performance by a factor 2-3289    if (c in goog.json.Serializer.charToJsonCharCache_) {290      return goog.json.Serializer.charToJsonCharCache_[c];291    }292293    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) { // \u1000300      rv += '0';301    }302    return goog.json.Serializer.charToJsonCharCache_[c] = rv + cc.toString(16);303  }), '"');304};305306307/**308 * Serializes a number to a JSON string309 * @private310 * @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};316317318/**319 * Serializes an array to a JSON string320 * @param {Array} arr The array to serialize.321 * @param {Array} sb Array used as a string builder.322 * @protected323 */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);330331    var value = arr[i];332    this.serializeInternal(333        this.replacer_ ? this.replacer_.call(arr, String(i), value) : value,334        sb);335336    sep = ',';337  }338  sb.push(']');339};340341342/**343 * Serializes an object to a JSON string344 * @private345 * @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(':');360361        this.serializeInternal(362            this.replacer_ ? this.replacer_.call(obj, key, value) : value,363            sb);364365        sep = ',';366      }367    }368  }369  sb.push('}');370};