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(typeof o == "undefined" || o === null){
36 }else if(Ext.isArray(o)){
37 return encodeArray(o);
38 }else if(Object.prototype.toString.apply(o) === '[object Date]'){
39 return Ext.util.JSON.encodeDate(o);
40 }else if(typeof o == "string"){
41 return encodeString(o);
42 }else if(typeof o == "number"){
43 return isFinite(o) ? String(o) : "null";
44 }else if(typeof o == "boolean"){
47 var a = ["{"], b, i, v;
49 if(!useHasOwn || o.hasOwnProperty(i)) {
60 a.push(doEncode(i), ":",
61 v === null ? "null" : doEncode(v));
79 encodeString = function(s){
80 if (/["\\\x00-\x1f]/.test(s)) {
81 return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
88 Math.floor(c / 16).toString(16) +
89 (c % 16).toString(16);
94 encodeArray = function(o){
95 var a = ["["], b, i, l = o.length, v;
96 for (i = 0; i < l; i += 1) {
107 a.push(v === null ? "null" : Ext.util.JSON.encode(v));
115 this.encodeDate = function(o){
116 return '"' + o.getFullYear() + "-" +
117 pad(o.getMonth() + 1) + "-" +
118 pad(o.getDate()) + "T" +
119 pad(o.getHours()) + ":" +
120 pad(o.getMinutes()) + ":" +
121 pad(o.getSeconds()) + '"';
125 * Encodes an Object, Array or other value
126 * @param {Mixed} o The variable to encode
127 * @return {String} The JSON string
129 this.encode = function() {
133 // setup encoding function on first access
134 ec = isNative() ? JSON.stringify : doEncode;
142 * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError unless the safe option is set.
143 * @param {String} json The JSON string
144 * @return {Object} The resulting object
146 this.decode = function() {
148 return function(json) {
150 // setup decoding function on first access
151 dc = isNative() ? JSON.parse : doDecode;
159 * Shorthand for {@link Ext.util.JSON#encode}
160 * @param {Mixed} o The variable to encode
161 * @return {String} The JSON string
165 Ext.encode = Ext.util.JSON.encode;
167 * Shorthand for {@link Ext.util.JSON#decode}
168 * @param {String} json The JSON string
169 * @param {Boolean} safe (optional) Whether to return null or throw an exception if the JSON is invalid.
170 * @return {Object} The resulting object
174 Ext.decode = Ext.util.JSON.decode;