Alain Roger wrote:
Hi,

i didn't find anything on jQuery and JSON. is there any decoder ?
thanks a lot.

jQuery just does an "eval" on JSON. so no data checking

If you want data checking, go to http://json.org, and download the javascript JSON implementation.
They do change the array and object prototypes, breaking some apps..
So here's my stripped version, as plain functions to call (no warranties):

//  mediaBeez version of http://json.org/json.js dated 2007-09-27
//  all functions taken out of array and object prototypes, so as not
//  to break apps that iterate through all values in an array.

function arrayToJSONstring (ar) {
   var a = [], v;

   for (var i = 0; i < ar.length; i += 1) {
   v = ar[i];
   switch (typeof v) {
       case 'object':
           if (v) {
               a.push(objectToJSONstring(v));
           } else {
               a.push('null');
           }
           break;

       case 'string':
           a.push(stringToJSONstring(v)); break;
       case 'number':
           a.push(numberToJSONstring(v)); break;
       case 'boolean':
           a.push(booleanToJSONstring(v)); break;
       }
   }
return '[' + a.join(',') + ']'; // Join all of the member texts together and wrap them in brackets.
};

function booleanToJSONstring (b) {
   return String(b);
};

function dateToJSONstring (dt) {

// Ultimately, this method will be equivalent to the date.toISOString method.

   function f(n) { // Format integers to have at least two digits.
       return n < 10 ? '0' + n : n;
   }

   return '"' + dt.getFullYear() + '-' +
       f(dt.getMonth() + 1) + '-' +
       f(dt.getDate()) + 'T' +
       f(dt.getHours()) + ':' +
       f(dt.getMinutes()) + ':' +
       f(dt.getSeconds()) + '"';
};

function numberToJSONstring (num) {
// JSON numbers must be finite. Encode non-finite numbers as null.
   return isFinite(num) ? String(num) : 'null';
};

function JSONencode (val) {
   var sv;
   switch (typeof val) {
   case "object":
       if (val==null) {
           sv = "null";
       } else if (val.length) {
           sv = arrayToJSONstring (val);
       } else {
           sv = objectToJSONstring (val);
       }
       break;
   case 'string': sv = stringToJSONstring (val); break;
   case 'number': sv = numberToJSONstring (val); break;
   case 'boolean' : sv = booleanToJSONstring (val); break;
   }
   return sv;
}
function objectToJSONstring (ob) {
   var a = [],     // The array holding the member texts.
       k,          // The current key.
       v,          // The current value.
sk, sv;

// Iterate through all of the keys in the object, ignoring the proto chain.

   for (k in ob) {
       if (ob.hasOwnProperty(k)) {
           switch (typeof k) {
               case 'object': sk = objectToJSONstring (k); break;
               case 'string': sk = stringToJSONstring (k); break;
               case 'number': sk = numberToJSONstring (k); break;
               case 'boolean' : sk = booleanToJSONstring (k); break;
           }
           v = ob[k];
           switch (typeof v) {
           case 'object':
               if (v == null) {
                   sv = 'null';
               } else if (v.length) {
                   sv = arrayToJSONstring(v);
               } else {
                   sv =  objectToJSONstring(v);
               }
               break;

           case 'string':
               sv = stringToJSONstring(v);
               break;
           case 'number':
               sv = numberToJSONstring(v);
               break;
           case 'boolean':
               sv = booleanToJSONstring(v);
               break;
           }

           a.push (sk + ':' + sv);

       }
   }

   return '{' + a.join(',') + '}';
};

function JSONstringDecode (str, filter) {
   var j;
//mb.reportToDebugger ('JSD: '+str, true);

   function walk(k, v) {
       var i;
       if (v && typeof v === 'object') {
           for (i in v) {
               if (v.hasOwnProperty(i)) {
                   v[i] = walk(i, v[i]);
               }
           }
       }
       return filter(k, v);
   }


// Parsing happens in three stages. In the first stage, we run the text against // a regular expression which looks for non-JSON characters. We are especially // concerned with '()' and 'new' because they can cause invocation, and '=' // because it can cause mutation. But just to be safe, we will reject all
   // unexpected characters.


//modified regexp (by rel. noob); now accepts input like:
//{'g':[{'desktopID':'action=viewArticle&target=frontpage&language=1788'}]}
//and
//

   if (/^[,:{}\<\>\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/.test(str.
       replace(/\\./g, '@').
       replace(/['"][^"\\\n\r]*['"]/g, ''))) {

       try {
           j = eval('(' + str + ')');
           return j;
       } catch (e) {
           mb.error ('parseJSON: '+str);
           throw new SyntaxError('parseJSON');
       }
   } else {
       mb.error ('parseJSON: '+str);
       throw new SyntaxError('parseJSON');
   }

// In the optional third stage, we recursively walk the new structure, passing // each name/value pair to a filter function for possible transformation.

   if (typeof filter === 'function') {
       j = walk('', j);
   }
   return j;
};


function stringToJSONstring (str) {
   // m is a table of character substitutions.
   var m = {
   '\b': '\\b',
   '\t': '\\t',
   '\n': '\\n',
   '\f': '\\f',
   '\r': '\\r',
   '"' : '\\"',
   '\\': '\\\\'
   };

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can simply slap some quotes around it.
// Otherwise we must also replace the offending characters with safe
// sequences.

   if (/["\\\x00-\x1f]/.test(str)) {
       return '"' + str.replace(/[\x00-\x1f\\"]/g, function (a) {
           var c = m[a];
           if (c) {
               return c;
           }
           c = a.charCodeAt();
return '\\u00' + Math.floor(c / 16).toString(16) +(c % 16).toString(16);
       }) + '"';
   }
   return '"' + str + '"';
}


Reply via email to