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