Upgrade to ExtJS 4.0.2 - Released 06/09/2011
[extjs.git] / src / core / src / misc / JSON.js
1 /*
2
3 This file is part of Ext JS 4
4
5 Copyright (c) 2011 Sencha Inc
6
7 Contact:  http://www.sencha.com/contact
8
9 GNU General Public License Usage
10 This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file.  Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html.
11
12 If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact.
13
14 */
15 /**
16  * @class Ext.JSON
17  * Modified version of Douglas Crockford"s json.js that doesn"t
18  * mess with the Object prototype
19  * http://www.json.org/js.html
20  * @singleton
21  */
22 Ext.JSON = new(function() {
23     var useHasOwn = !! {}.hasOwnProperty,
24     isNative = function() {
25         var useNative = null;
26
27         return function() {
28             if (useNative === null) {
29                 useNative = Ext.USE_NATIVE_JSON && window.JSON && JSON.toString() == '[object JSON]';
30             }
31
32             return useNative;
33         };
34     }(),
35     pad = function(n) {
36         return n < 10 ? "0" + n : n;
37     },
38     doDecode = function(json) {
39         return eval("(" + json + ')');
40     },
41     doEncode = function(o) {
42         if (!Ext.isDefined(o) || o === null) {
43             return "null";
44         } else if (Ext.isArray(o)) {
45             return encodeArray(o);
46         } else if (Ext.isDate(o)) {
47             return Ext.JSON.encodeDate(o);
48         } else if (Ext.isString(o)) {
49             return encodeString(o);
50         } else if (typeof o == "number") {
51             //don't use isNumber here, since finite checks happen inside isNumber
52             return isFinite(o) ? String(o) : "null";
53         } else if (Ext.isBoolean(o)) {
54             return String(o);
55         } else if (Ext.isObject(o)) {
56             return encodeObject(o);
57         } else if (typeof o === "function") {
58             return "null";
59         }
60         return 'undefined';
61     },
62     m = {
63         "\b": '\\b',
64         "\t": '\\t',
65         "\n": '\\n',
66         "\f": '\\f',
67         "\r": '\\r',
68         '"': '\\"',
69         "\\": '\\\\',
70         '\x0b': '\\u000b' //ie doesn't handle \v
71     },
72     charToReplace = /[\\\"\x00-\x1f\x7f-\uffff]/g,
73     encodeString = function(s) {
74         return '"' + s.replace(charToReplace, function(a) {
75             var c = m[a];
76             return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
77         }) + '"';
78     },
79     encodeArray = function(o) {
80         var a = ["[", ""],
81         // Note empty string in case there are no serializable members.
82         len = o.length,
83         i;
84         for (i = 0; i < len; i += 1) {
85             a.push(doEncode(o[i]), ',');
86         }
87         // Overwrite trailing comma (or empty string)
88         a[a.length - 1] = ']';
89         return a.join("");
90     },
91     encodeObject = function(o) {
92         var a = ["{", ""],
93         // Note empty string in case there are no serializable members.
94         i;
95         for (i in o) {
96             if (!useHasOwn || o.hasOwnProperty(i)) {
97                 a.push(doEncode(i), ":", doEncode(o[i]), ',');
98             }
99         }
100         // Overwrite trailing comma (or empty string)
101         a[a.length - 1] = '}';
102         return a.join("");
103     };
104
105     /**
106      * <p>Encodes a Date. This returns the actual string which is inserted into the JSON string as the literal expression.
107      * <b>The returned value includes enclosing double quotation marks.</b></p>
108      * <p>The default return format is "yyyy-mm-ddThh:mm:ss".</p>
109      * <p>To override this:</p><pre><code>
110      Ext.JSON.encodeDate = function(d) {
111      return d.format('"Y-m-d"');
112      };
113      </code></pre>
114      * @param {Date} d The Date to encode
115      * @return {String} The string literal to use in a JSON string.
116      */
117     this.encodeDate = function(o) {
118         return '"' + o.getFullYear() + "-" 
119         + pad(o.getMonth() + 1) + "-"
120         + pad(o.getDate()) + "T"
121         + pad(o.getHours()) + ":"
122         + pad(o.getMinutes()) + ":"
123         + pad(o.getSeconds()) + '"';
124     };
125
126     /**
127      * Encodes an Object, Array or other value
128      * @param {Mixed} o The variable to encode
129      * @return {String} The JSON string
130      */
131     this.encode = function() {
132         var ec;
133         return function(o) {
134             if (!ec) {
135                 // setup encoding function on first access
136                 ec = isNative() ? JSON.stringify : doEncode;
137             }
138             return ec(o);
139         };
140     }();
141
142
143     /**
144      * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError unless the safe option is set.
145      * @param {String} json The JSON string
146      * @param {Boolean} safe (optional) Whether to return null or throw an exception if the JSON is invalid.
147      * @return {Object} The resulting object
148      */
149     this.decode = function() {
150         var dc;
151         return function(json, safe) {
152             if (!dc) {
153                 // setup decoding function on first access
154                 dc = isNative() ? JSON.parse : doDecode;
155             }
156             try {
157                 return dc(json);
158             } catch (e) {
159                 if (safe === true) {
160                     return null;
161                 }
162                 Ext.Error.raise({
163                     sourceClass: "Ext.JSON",
164                     sourceMethod: "decode",
165                     msg: "You're trying to decode an invalid JSON String: " + json
166                 });
167             }
168         };
169     }();
170
171 })();
172 /**
173  * Shorthand for {@link Ext.JSON#encode}
174  * @param {Mixed} o The variable to encode
175  * @return {String} The JSON string
176  * @member Ext
177  * @method encode
178  */
179 Ext.encode = Ext.JSON.encode;
180 /**
181  * Shorthand for {@link Ext.JSON#decode}
182  * @param {String} json The JSON string
183  * @param {Boolean} safe (optional) Whether to return null or throw an exception if the JSON is invalid.
184  * @return {Object} The resulting object
185  * @member Ext
186  * @method decode
187  */
188 Ext.decode = Ext.JSON.decode;
189
190