1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 goog.provide('cvox.ChromeVoxJSON');
9 * @fileoverview A simple wrapper around the JSON APIs.
10 * If it is possible to use the browser's built in native JSON, then
11 * cvox.ChromeVoxJSON is the same as JSON.
12 * If the page has its own version of JSON, cvox.ChromeVoxJSON will use its
13 * own implementation (rather than the version of JSON on the page
14 * which may be outdated/broken).
17 if (!cvox.ChromeVoxJSON) {
18 /** Placeholder object. */
19 cvox.ChromeVoxJSON = {};
22 if (window.JSON && window.JSON.toString() == '[object JSON]') {
23 cvox.ChromeVoxJSON = window.JSON;
26 * JSON implementation renamed to cvox.ChromeVoxJSON.
27 * This only gets called if the page has its own version of JSON.
30 * http://www.JSON.org/json2.js
35 * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
37 * See http://www.JSON.org/js.html
41 // Format integers to have at least two digits.
42 return n < 10 ? '0' + n : n;
45 if (typeof Date.prototype.toJSON !== 'function') {
47 Date.prototype.toJSON = function(key) {
49 return isFinite(this.valueOf()) ?
50 this.getUTCFullYear() + '-' +
51 f(this.getUTCMonth() + 1) + '-' +
52 f(this.getUTCDate()) + 'T' +
53 f(this.getUTCHours()) + ':' +
54 f(this.getUTCMinutes()) + ':' +
55 f(this.getUTCSeconds()) + 'Z' : 'null';
58 String.prototype.toJSON =
59 Number.prototype.toJSON =
60 Boolean.prototype.toJSON = function(key) {
61 return /** @type {string} */ (this.valueOf());
65 var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
66 escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
69 meta = { // table of character substitutions
81 function quote(string) {
83 // If the string contains no control characters, no quote characters, and
84 // no backslash characters, then we can safely slap some quotes around it.
85 // Otherwise we must also replace the offending characters with safe
88 escapable.lastIndex = 0;
89 return escapable.test(string) ?
90 '"' + string.replace(escapable, function(a) {
92 return typeof c === 'string' ? c :
93 '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
99 function str(key, holder) {
101 // Produce a string from holder[key].
103 var i, // The loop counter.
104 k, // The member key.
105 v, // The member value.
111 // If the value has a toJSON method, call it to obtain a replacement
114 if (value && typeof value === 'object' &&
115 typeof value.toJSON === 'function') {
116 value = value.toJSON(key);
119 // If we were called with a replacer function, then call the replacer to
120 // obtain a replacement value.
122 if (typeof rep === 'function') {
123 value = rep.call(holder, key, value);
126 // What happens next depends on the value's type.
128 switch (typeof value) {
133 // JSON numbers must be finite. Encode non-finite numbers as null.
134 return isFinite(value) ? String(value) : 'null';
138 // If the value is a boolean or null, convert it to a string. Note:
139 // typeof null does not produce 'null'. The case is included here in
140 // the remote chance that this gets fixed someday.
141 return String(value);
143 // If the type is 'object', we might be dealing with an object or an
148 // Due to a specification blunder in ECMAScript, typeof null is
149 // 'object', so watch out for that case.
155 // Make an array to hold the partial results of stringifying this
161 // Is the value an array?
163 if (Object.prototype.toString.apply(value) === '[object Array]') {
165 // The value is an array. Stringify every element. Use null as a
166 // placeholder for non-JSON values.
168 length = value.length;
169 for (i = 0; i < length; i += 1) {
170 partial[i] = str(i, value) || 'null';
173 // Join all of the elements together, separated with commas, and
174 // wrap them in brackets.
176 v = partial.length === 0 ? '[]' :
178 partial.join(',\n' + gap) + '\n' +
180 '[' + partial.join(',') + ']';
185 // If the replacer is an array, use it to select the members to be
188 if (rep && typeof rep === 'object') {
190 for (i = 0; i < length; i += 1) {
192 if (typeof k === 'string') {
195 partial.push(quote(k) + (gap ? ': ' : ':') + v);
201 // Otherwise, iterate through all of the keys in the object.
203 if (Object.hasOwnProperty.call(value, k)) {
206 partial.push(quote(k) + (gap ? ': ' : ':') + v);
212 // Join all of the member texts together, separated with commas,
213 // and wrap them in braces.
215 v = partial.length === 0 ? '{}' :
216 gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
217 mind + '}' : '{' + partial.join(',') + '}';
223 // If the JSON object does not yet have a stringify method, give it one.
225 if (typeof cvox.ChromeVoxJSON.stringify !== 'function') {
227 * @param {*} value Input object.
228 * @param {(Array<string>|(function(string, *) : *)|null)=} replacer
229 * Replacer array or function.
230 * @param {(number|string|null)=} space Whitespace character.
231 * @return {string} json string which represents jsonObj.
233 cvox.ChromeVoxJSON.stringify = function(value, replacer, space) {
235 // The stringify method takes a value and an optional replacer, and an
236 // optional space parameter, and returns a JSON text. The replacer can
237 // be a function that can replace values, or an array of strings that
238 // will select the keys. A default replacer method can be provided. Use
239 // of the space parameter can produce text that is more easily readable.
245 // If the space parameter is a number, make an indent string containing
248 if (typeof space === 'number') {
249 for (i = 0; i < space; i += 1) {
253 // If the space parameter is a string, it will be used as the indent
256 } else if (typeof space === 'string') {
260 // If there is a replacer, it must be a function or an array.
261 // Otherwise, throw an error.
264 if (replacer && typeof replacer !== 'function' &&
265 (typeof replacer !== 'object' ||
266 typeof replacer.length !== 'number')) {
267 throw new Error('JSON.stringify');
270 // Make a fake root object containing our value under the key of ''.
271 // Return the result of stringifying the value.
273 return str('', {'': value});
278 // If the JSON object does not yet have a parse method, give it one.
280 if (typeof cvox.ChromeVoxJSON.parse !== 'function') {
282 * @param {string} text The string to parse.
283 * @param {(function(string, *) : *|null)=} reviver Reviver function.
284 * @return {*} The JSON object.
286 cvox.ChromeVoxJSON.parse = function(text, reviver) {
288 // The parse method takes a text and an optional reviver function, and
289 // returns a JavaScript value if the text is a valid JSON text.
293 function walk(holder, key) {
295 // The walk method is used to recursively walk the resulting structure
296 // so that modifications can be made.
298 var k, v, value = holder[key];
299 if (value && typeof value === 'object') {
301 if (Object.hasOwnProperty.call(value, k)) {
303 if (v !== undefined) {
311 return reviver.call(holder, key, value);
315 // Parsing happens in four stages. In the first stage, we replace
316 // certain Unicode characters with escape sequences. JavaScript handles
317 // many characters incorrectly, either silently deleting them, or
318 // treating them as line endings.
323 text = text.replace(cx, function(a) {
325 ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
329 // In the second stage, we run the text against regular expressions that
330 // look for non-JSON patterns. We are especially concerned with '()' and
331 // 'new' because they can cause invocation, and '=' because it can cause
332 // mutation. But just to be safe, we want to reject all unexpected
334 // We split the second stage into 4 regexp operations in order to work
335 // around crippling inefficiencies in IE's and Safari's regexp engines.
336 // First we replace the JSON backslash pairs with '@' (a non-JSON
337 // character). Second, we replace all simple value tokens with ']'
338 // characters. Third, we delete all open brackets that follow a colon or
339 // comma or that begin the text. Finally, we look to see that the
340 // remaining characters are only whitespace or ']' or ',' or ':' or '{'
341 // or '}'. If that is so, then the text is safe for eval.
344 test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
345 replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
346 replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
348 // In the third stage we use the eval function to compile the text
349 // into a JavaScript structure. The '{' operator is subject to a
350 // syntactic ambiguity in JavaScript: it can begin a block or an
351 // object literal. We wrap the text in parens to eliminate the
354 j = eval('(' + text + ')');
356 // In the optional fourth stage, we recursively walk the new
357 // structure, passing each name/value pair to a reviver function for
358 // possible transformation.
359 return typeof reviver === 'function' ? walk({'': j}, '') : j;
362 // If the text is not JSON parseable, then a SyntaxError is thrown.
364 throw new SyntaxError('JSON.parse');