﻿
function formatJson(strJson, indentString)
{
	// Default to 4 spaces for the indent char
	if (typeof (indentString) !== "string")
		indentString = "    ";

	var nextLine_curly = false;
	var nextLine_square = false;

	var indent = 0;

	// newline function
	var nl = function (indentAdjust)
	{
		if (typeof (indentAdjust) === "number")
			indent += indentAdjust;

		var s = "\n";
		for (var i = 0; i < indent; ++i)
			s += indentString;
		return s;
	}

	var formatted = "";
	$.each(strJson, function (ix, chr)
	{
		var after = "";
		switch (chr)
		{
			case "{":
				// handle empty objects
				if (strJson[ix + 1] == "}")
				{
					formatted += chr;
				}
				else
				{
					formatted += (nextLine_curly ? nl() : "") + chr;
					formatted += nl(1);
				}
				break;

			case "}":
				// handle empty objects
				if (strJson[ix - 1] == "{")
					formatted += chr;
				else
					formatted += nl(-1) + chr;
				break;

			case "[":
				// handle empty arrays
				if (strJson[ix + 1] == "]")
				{
					formatted += chr;
				}
				else
				{
					formatted += (nextLine_square ? nl() : "") + chr + nl(1);
				}
				break;

			case "]":
				// handle empty arrays
				if (strJson[ix - 1] == "[")
					formatted += chr;
				else
					formatted += nl(-1) + chr;
				break;

			case ",":
				formatted += chr + nl();
				break;

			case ":":
				formatted += chr;
				if (strJson[ix + 1] != " ")
					formatted += " ";
				break;

			default:
				formatted += chr;
		}
	});
	return formatted;
}

