Over a million developers have joined DZone.

Simple JSON And Deep Clone

·

Object.prototype.deep_clone = function(){
	eval("var tmp = " + this.toJSON());
	return tmp;
}
Object.prototype.toJSON = function(){
	var json = [];
	for(var i in this){
		if(!this.hasOwnProperty(i)) continue;
		//if(typeof this[i] == "function") continue;
		json.push(
			i.toJSON() + " : " +
			((this[i] != null) ? this[i].toJSON() : "null")
		)
	}
	return "{\n " + json.join(",\n ") + "\n}";
}
Array.prototype.toJSON = function(){
	for(var i=0,json=[];i= ' ') ?
			(c == '\\') ? (tmp[i] = '\\\\'):
			(c == '"')  ? (tmp[i] = '\\"' ): 0 :
		(tmp[i] = 
			(c == '\n') ? '\\n' :
			(c == '\r') ? '\\r' :
			(c == '\t') ? '\\t' :
			(c == '\b') ? '\\b' :
			(c == '\f') ? '\\f' :
			(c = c.charCodeAt(),('\\u00' + ((c>15)?1:0)+(c%16)))
		)
	}
	return '"' + tmp.join("") + '"';
}



var json = {
 str : "abcde",
 num : 6,
 reg : /foobar/i,
 array : [1,2,3,4,5],
 func : function(x,y){return x+y},
 obj : {a : "b"}
}.toJSON();

alert(json);
// result
{
 "str" : "abcde",
 "num" : 6,
 "reg" : /foobar/i,
 "array" : [1, 2, 3, 4, 5],
 "func" : function(x,y){return x+y},
 "obj" : {
 "a" : "b"
}
}
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}