JSON encoder
An implementation of JSON.stringify in JS. (NOTE: many browsers now have JSON.stringify)
by doug65536
JavaScript
window.encode_json = (function () {
function encode_json_string(result, obj) {
var ch;
result.s += '"';
for (var i = 0; i < obj.length; ++i) {
ch = obj[i];
switch (ch) {
case '"':
result.s += '\\"';
break;
case '\\':
result.s += '\\\\';
break;
case '\b':
result.s += '\\b';
break;
case '\f':
result.s += '\\f';
break;
case '\n':
result.s += '\\n';
break;
case '\r':
result.s += '\\r';
break;
case '\t':
result.s += '\\t';
break;
default:
var code = ch.charCodeAt(0);
result.s += code >= 32 ? ch : '\\u' + ("000" + code.toString(16)).substr(-4);
}
}
result.s += '"';
}
function encode_json_value(result, obj) {
switch (obj) {
case null:
result.s += 'null';
break;
case true:
result.s += 'true';
break;
case false:
result.s += 'false';
break;
default:
switch (typeof obj) {
case 'number':
result.s += obj;
break;
case 'string':
encode_json_string(result, obj);
break;
case 'object':
if (obj instanceof Array) {
encode_json_array(result, obj);
} else {
encode_json_object(result, obj);
}
...