
| home | AJAX (6) || C#.NET (5) || Coldfusion Development (16) || DHTML (14) || Flash Development (19) || jQuery (4) || MSSQL (2) || UNIX (10) |
| 4.11.08 | Mark Gibson’s JSON JQuery Updated |
Mark Gibson put together a re-purposed json.js direct from Douglas Crockford’s early implementation of json.js as a jQuery plugin located here. I simply took Douglas Crockford’s ‘2008-02-14′ json2.js release and did the same re-purposing as Mark Gibson did just to have the updated features of the new json2.js code. One of those features included the ability to detect enumerable object to differentiate between Array() and Object(), [] vs {}.
The code below only offers the $.toJSON() jQuery function to take a Javascript object serialize it into a JSON string and return said string. This is hugely important for our AJAX functionality which posts JSON data instead of itemized form fields in the POST data string.
I also did not include the Date.prototype.toJSON just because of the possible conflicts with jQuery and that we don’t need to parse dates specifically that way for our use.
switch (typeof value) {
case 'string':
return r.test(value) ?
'"
case 'number':
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
return String(value);
case 'object':
if (!value) {
return 'null';
}
if (typeof value.toJSON === 'function') {
return $.toJSON(value.toJSON());
}
a = [];
if (typeof value.length === 'number' &&
!(value.propertyIsEnumerable('length'))) {
l = value.length;
for (i = 0; i < l; i += 1) {
a.push($.toJSON(value[i], whitelist) || 'null');
}
return '[' + a.join(',') + ']';
}
if (whitelist) {
l = whitelist.length;
for (i = 0; i < l; i += 1) {
k = whitelist[i];
if (typeof k === 'string') {
v = $.toJSON(value[k], whitelist);
if (v) {
a.push($.toJSON(k) + ':' + v);
}
}
}
} else {
for (k in value) {
if (typeof k === 'string') {
v = $.toJSON(value[k], whitelist);
if (v) {
a.push($.toJSON(k) + ':' + v);
}
}
}
}
return '{' + a.join(',') + '}';
}
};
})(jQuery);
Download this code: jQuery.toJSON.js
No comments