Since starting Javascript and especially AJAX, I’ve found myself in a lot of situations where I would have loved to have a Javascript Object/Array to JSON converter, but I never found one. Even in jQuery, which has parseJSON, it didn’t have something that went the other way round.
So I decided to create it myself.
And, as I’ve found myself sending this code around to quite a few developers who’ve asked, I thought I might as well put it up on my blog.
Pretty straight forward, simple pass an object or array into JSONString and it’ll return a JSON String.
function JSONString(object) {
var jsonString = '';
var first = true;
if(typeof(object) != 'object' || object === null || object === undefined) return false;
if(object.constructor.toString().indexOf("Array") == -1) jsonString += '{'; else jsonString += '[';
if(object.constructor.toString().indexOf("Array") == -1) {
for(var idx in object) {
if(!first) jsonString += ',';
first = false;
if(object.constructor.toString().indexOf("Array") == -1){
if(typeof(idx) == 'string') {
jsonString += '"' + idx + '"';
} else {
jsonString += idx;
}
jsonString += ':';
}
switch(typeof(object[idx])) {
case 'number':
jsonString += object[idx];
break;
case 'string':
jsonString += '"' + object[idx].replace(/"/gi,'\\"') + '"';
break;
case 'object':
jsonString += JSONString(object[idx]);
break;
case 'boolean':
jsonString += ((object[idx])? 'true' : 'false');
break;
case 'function':
jsonString += 'function';
break;
}
}
}
else {
for(var idx = 0; idx < object.length; idx++) {
if(!first) jsonString += ',';
first = false;
switch(typeof(object[idx])) {
case 'number':
jsonString += object[idx];
break;
case 'string':
jsonString += '"' + object[idx] + '"';
break;
case 'object':
jsonString += JSONString(object[idx]);
break;
case 'boolean':
jsonString += ((object[idx])? 'true' : 'false');
break;
case 'function':
jsonString += 'function';
break;
}
}
}
if(object.constructor.toString().indexOf("Array") == -1) jsonString += '}'; else jsonString += ']';
return jsonString.replace(/(\r\n|\n|\r)/gm,"");
}