3 * Copyright(c) 2006-2009 Ext JS, LLC
5 * http://www.extjs.com/license
9 * Modified version of Douglas Crockford"s json.js that doesn"t
10 * mess with the Object prototype
11 * http://www.json.org/js.html
14 Ext.util.JSON = new (function(){
15 var useHasOwn = !!{}.hasOwnProperty,
16 isNative = function() {
20 if (useNative === null) {
21 useNative = Ext.USE_NATIVE_JSON && window.JSON && JSON.toString() == '[object JSON]';
28 return n < 10 ? "0" + n : n;
30 doDecode = function(json){
31 return eval("(" + json + ')');
33 doEncode = function(o){
34 if(!Ext.isDefined(o) || o === null){
36 }else if(Ext.isArray(o)){
37 return encodeArray(o);
38 }else if(Ext.isDate(o)){
39 return Ext.util.JSON.encodeDate(o);
40 }else if(Ext.isString(o)){
41 return encodeString(o);
42 }else if(typeof o == "number"){
43 //don't use isNumber here, since finite checks happen inside isNumber
44 return isFinite(o) ? String(o) : "null";
45 }else if(Ext.isBoolean(o)){
48 var a = ["{"], b, i, v;
50 // don't encode DOM objects
51 if(!o.getElementsByTagName){
52 if(!useHasOwn || o.hasOwnProperty(i)) {
63 a.push(doEncode(i), ":",
64 v === null ? "null" : doEncode(v));
83 encodeString = function(s){
84 if (/["\\\x00-\x1f]/.test(s)) {
85 return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
92 Math.floor(c / 16).toString(16) +
93 (c % 16).toString(16);
98 encodeArray = function(o){
99 var a = ["["], b, i, l = o.length, v;
100 for (i = 0; i < l; i += 1) {
111 a.push(v === null ? "null" : Ext.util.JSON.encode(v));
119 this.encodeDate = function(o){
120 return '"' + o.getFullYear() + "-" +
121 pad(o.getMonth() + 1) + "-" +
122 pad(o.getDate()) + "T" +
123 pad(o.getHours()) + ":" +
124 pad(o.getMinutes()) + ":" +
125 pad(o.getSeconds()) + '"';
129 * Encodes an Object, Array or other value
130 * @param {Mixed} o The variable to encode
131 * @return {String} The JSON string
133 this.encode = function() {
137 // setup encoding function on first access
138 ec = isNative() ? JSON.stringify : doEncode;
146 * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError unless the safe option is set.
147 * @param {String} json The JSON string
148 * @return {Object} The resulting object
150 this.decode = function() {
152 return function(json) {
154 // setup decoding function on first access
155 dc = isNative() ? JSON.parse : doDecode;
163 * Shorthand for {@link Ext.util.JSON#encode}
164 * @param {Mixed} o The variable to encode
165 * @return {String} The JSON string
169 Ext.encode = Ext.util.JSON.encode;
171 * Shorthand for {@link Ext.util.JSON#decode}
172 * @param {String} json The JSON string
173 * @param {Boolean} safe (optional) Whether to return null or throw an exception if the JSON is invalid.
174 * @return {Object} The resulting object
178 Ext.decode = Ext.util.JSON.decode;