Debian Codegraph @

closure-library/closure/goog/json/hybrid.js

raw
1 // Copyright 2013 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 /**
17 * @fileoverview Utility to attempt native JSON processing, falling back to
18 * goog.json if not available.
19 *
20 * This is intended as a drop-in for current users of goog.json who want
21 * to take advantage of native JSON if present.
22 *
23 * @author [email protected] (Nathan Naze)
24 */
25
26 goog.provide('goog.json.hybrid');
27
28 goog.require('goog.asserts');
29 goog.require('goog.json');
30
31
32 /**
33 * Attempts to serialize the JSON string natively, falling back to
34 * {@code goog.json.serialize} if unsuccessful.
35 * @param {!Object} obj JavaScript object to serialize to JSON.
36 * @return {string} Resulting JSON string.
37 */
38 goog.json.hybrid.stringify =
39 goog.json.USE_NATIVE_JSON ? goog.global['JSON']['stringify'] : function(
40 obj) {
41 if (goog.global.JSON) {
42 try {
43 return goog.global.JSON.stringify(obj);
44 } catch (e) {
45 // Native serialization failed. Fall through to retry with
46 // goog.json.serialize.
47 }
48 }
49
50 return goog.json.serialize(obj);
51 };
52
53
54 /**
55 * Attempts to parse the JSON string natively, falling back to
56 * the supplied {@code fallbackParser} if unsuccessful.
57 * @param {string} jsonString JSON string to parse.
58 * @param {function(string):Object} fallbackParser Fallback JSON parser used
59 * if native
60 * @return {?Object} Resulting JSON object.
61 * @private
62 */
63 goog.json.hybrid.parse_ = function(jsonString, fallbackParser) {
64 if (goog.global.JSON) {
65 try {
66 var obj = goog.global.JSON.parse(jsonString);
67 goog.asserts.assert(typeof obj == 'object');
68 return /** @type {?Object} */ (obj);
69 } catch (e) {
70 // Native parse failed. Fall through to retry with goog.json.parse.
71 }
72 }
73
74 return fallbackParser(jsonString);
75 };
76
77
78 /**
79 * Attempts to parse the JSON string natively, falling back to
80 * {@code goog.json.parse} if unsuccessful.
81 * @param {string} jsonString JSON string to parse.
82 * @return {?Object} Resulting JSON object.
83 */
84 goog.json.hybrid.parse =
85 goog.json.USE_NATIVE_JSON ? goog.global['JSON']['parse'] : function(
86 jsonString) {
87 return goog.json.hybrid.parse_(jsonString, goog.json.parse);
88 };