Javascript dump or print_r output or toSource() alternative output

You can use JSON.stringify to receive a JSON-style string, but sometimes you want an actual javascript notation, not just object notation. In that case, it’s tough to find a reasonable output. I’ve heard that firefox has a toSource method of objects that outputs something like I needed, but I wanted cross-browser compatibility. Here’s how I did it:

function dump(obj, pad)
{
	var output = "";
		if(!pad)
	{
		pad = "";
	}
		if(Array.isArray(obj))
	{
		output +="[\n ";
		for(var o in obj)
		{
			output += "\t"+pad+dump(obj[o], pad+"\t")+",\n";
		}
		output = output.slice(0,-2);
		output +="\n"+pad+"]";
	}
	else if(typeof(obj)==="object")
	{
		output +="{\n ";
		for(var o in obj)
		{
			output += "\t"+pad+o + ":" + dump(obj[o], pad+"\t") + ",\n";
		}
		output = output.slice(0,-2);
		output +="\n"+pad+"}";
	}
	else if(typeof(obj)==="string")
	{
		output += "\"" + obj.replace("\"", "\\\"") + "\"";
	}
	else if(typeof(obj)!=="function")
	{
		output += obj.toString();
	}
	else
	{
		output += "\"FUNCTION\"";
	}
	return output;
}

Leave a Reply

Your email address will not be published. Required fields are marked *