Created
April 6, 2011 08:31
-
-
Save odiak/905332 to your computer and use it in GitHub Desktop.
jquery extension.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
jQuery.encodeJSON = function ($) { | |
var enc = function (data) { | |
var res = "", a, b; | |
switch (typeof data) { | |
case "number" : | |
return data + ""; | |
case "string" : | |
res = escape(data); | |
res = res.replace(/%[^%]+/g, function (c) { | |
return c.replace(/%u?/, function () { | |
var res = "\\u"; | |
for (var a = 0; a < (4 + 1) - c.length; a ++) { | |
res += "0"; | |
} | |
return res; | |
}); | |
}); | |
return "\"" + res + "\""; | |
case "object" : | |
if ($.isArray(data)) { | |
res = ""; | |
for (a = 0; a < data.length; a ++) { | |
if (a) { | |
res += ","; | |
} | |
res += enc(data[a]); | |
} | |
return "[" + res + "]"; | |
} | |
else if (data === null) { | |
return "null"; | |
} | |
else { | |
b = 0; | |
res = ""; | |
for (a in data) { | |
if (data.hasOwnProperty(a)) { | |
b ? (res += ",") : (b ++); | |
res += enc(a); | |
res += ":"; | |
res += enc(data[a]); | |
} | |
} | |
return "{" + res + "}"; | |
} | |
case "boolean": | |
return data ? "true" : "false"; | |
default : | |
return enc(null); | |
} | |
}; | |
return enc; | |
}(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment