Skip to content

Instantly share code, notes, and snippets.

@odiak
Created April 6, 2011 08:31
Show Gist options
  • Save odiak/905332 to your computer and use it in GitHub Desktop.
Save odiak/905332 to your computer and use it in GitHub Desktop.
jquery extension.
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