JSON jQuery Plugin
Agile Web Application Development with Yii 1.1 and PHP5
I finally got a bit of time and I started playing around with the creation of jQuery plugins and did created a couple of them that I believe all of you will find useful, one of them is a JSON plugin.
As you all know jQuery do not have a JSON encode function. I truly do not know the reason why but to implement it was quite easy -maybe the guys from jQuery thought that it wasn’t really necessary and I agree with them. Most of us use JSON on the server side through PHP or whatever the server tech we use but sometimes, and I repeat, sometimes, we require to develop client applications that by using JSON (thanks David Crockford) we can reduce our server resources and the amount of data transmitted between client and server. But this is a subject that I will treat in the next posts.
Here is the plugin code:
jQuery.JSON = {
useHasOwn : ({}.hasOwnProperty ? true : false),
pad : function(n) {
return n < 10 ? "0" + n : n;
},
m : {
"\b": '\\b',
"\t": '\\t',
"\n": '\\n',
"\f": '\\f',
"\r": '\\r',
'"' : '\\"',
"\\": '\\\\'
},
encodeString : function(s){
if (/["\\\x00-\x1f]/.test(s)) {
return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
var c = m[b];
if(c){
return c;
}
c = b.charCodeAt();
return "\\u00" +
Math.floor(c / 16).toString(16) +
(c % 16).toString(16);
}) + '"';
}
return '"' + s + '"';
},
encodeArray : function(o){
var a = ["["], b, i, l = o.length, v;
for (i = 0; i < l; i += 1) {
v = o[i];
switch (typeof v) {
case "undefined":
case "function":
case "unknown":
break;
default:
if (b) {
a.push(',');
}
a.push(v === null ? "null" : this.encode(v));
b = true;
}
}
a.push("]");
return a.join("");
},
encodeDate : function(o){
return '"' + o.getFullYear() + "-" +
pad(o.getMonth() + 1) + "-" +
pad(o.getDate()) + "T" +
pad(o.getHours()) + ":" +
pad(o.getMinutes()) + ":" +
pad(o.getSeconds()) + '"';
},
encode : function(o){
if(typeof o == "undefined" || o === null){
return "null";
}else if(o instanceof Array){
return this.encodeArray(o);
}else if(o instanceof Date){
return this.encodeDate(o);
}else if(typeof o == "string"){
return this.encodeString(o);
}else if(typeof o == "number"){
return isFinite(o) ? String(o) : "null";
}else if(typeof o == "boolean"){
return String(o);
}else {
var self = this;
var a = ["{"], b, i, v;
for (i in o) {
if(!this.useHasOwn || o.hasOwnProperty(i)) {
v = o[i];
switch (typeof v) {
case "undefined":
case "function":
case "unknown":
break;
default:
if(b){
a.push(',');
}
a.push(self.encode(i), ":",
v === null ? "null" : self.encode(v));
b = true;
}
}
}
a.push("}");
return a.join("");
}
},
decode : function(json){
return eval("(" + json + ')');
}
};
How to use
Copy and paste the above code onto a file and name it whatever you like, for the sake of the example we will call it jquery.json.js. And then configure your head section like this:
<!-- jquery library (if you dont have it, then download it--> <script language="javascript" src="jquery.1.3.2.js" ></script> <!-- our plugin file --> <script language="javascript" src="jquery.json.js"></script>
That’s it, now we can call our plugin like this:
// test variables
var obj = {json:'this is a test json property',xml:'this is a test xml property'};
var arr = ['A','B of 2 index array','C','D'];
// encoding an object
var a = $.JSON.encode(obj);
alert('json encoded object:'+a);
// decoding an object
var b = $.JSON.decode(a);
alert('json decoded object property:'+b.json);
// encoding an array
a = $.JSON.encode(arr);
alert('json encoded array:'+a);
// decoding the array
b = $.JSON.decode(a);
alert('json decoded array:'+b[1]);
On future posts we will make use of this plugin to show what we can do with it.
Tweet this!
Gracias, me sirvio en mi actual proyecto, solo una aclaración, si lo uso para enviar un array via ajax y decodificarlo en php primero debo aplicarle stripslashes a la cadena json.