Skip to content

Instantly share code, notes, and snippets.

@cloudchen
Created April 10, 2013 07:59
Show Gist options
  • Save cloudchen/5352689 to your computer and use it in GitHub Desktop.
Save cloudchen/5352689 to your computer and use it in GitHub Desktop.
stringify javascript variable >> It's useful when you want write javascript variable into html template >> It's much better than JSON.stringify() since that doesn't support stringify function data type
function stringify(obj, variable) {
var objLiteral = '';
if (typeof obj == 'object') {
objLiteral += variable + "=";
if (obj.constructor == Array) {
objLiteral += "[];\n";
} else {
objLiteral += "{};\n";
}
for (var item in obj) {
if (typeof obj[item] == 'object') {
objLiteral += stringify(obj[item], variable + "['" + item + "']");
} else if (typeof obj[item] == 'function') {
objLiteral += variable + "['" + item + "'] = " + obj[item].toString() + ";\n"
} else if (typeof obj[item] == 'string') {
objLiteral += variable + "['" + item + "'] = '" + obj[item].toString() + "';\n"
} else {
objLiteral += variable + "['" + item + "'] = " + obj[item].toString() + ";\n";
}
}
} else if(typeof obj == "string") {
objLiteral += variable + "='" + obj.toString() + "';\n";
} else {
objLiteral += variable + "=" + obj.toString() + ";\n";
}
return objLiteral;
}
@cloudchen
Copy link
Author

It supports primitive data type

var a = stringify(function(asd,bb){asd}, 'config');
console.log(a);

var a = stringify("asdf", 'config');
console.log(a);

var a = stringify(12, 'config');
console.log(a);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment