Skip to content

Instantly share code, notes, and snippets.

@wcoder
Forked from maskaravivek/JsonHelper.cs
Created August 23, 2015 21:09
Show Gist options
  • Save wcoder/c24050c166b139739301 to your computer and use it in GitHub Desktop.
Save wcoder/c24050c166b139739301 to your computer and use it in GitHub Desktop.
class JsonHelper
{
public static string FormatJson(string str, string indentString = "\t")
{
var indent = 0;
var quoted = false;
var sb = new StringBuilder();
for (var i = 0; i < str.Length; i++)
{
var ch = str[i];
switch (ch)
{
case '{':
case '[':
sb.Append(ch);
if (!quoted)
{
sb.AppendLine();
foreach (var e in Enumerable.Range(0, ++indent))
sb.Append(indentString);
}
break;
case '}':
case ']':
if (!quoted)
{
sb.AppendLine();
foreach (var e in Enumerable.Range(0, --indent))
sb.Append(indentString);
}
sb.Append(ch);
break;
case '"':
sb.Append(ch);
bool escaped = false;
var index = i;
while (index > 0 && str[--index] == '\\')
escaped = !escaped;
if (!escaped)
quoted = !quoted;
break;
case ',':
sb.Append(ch);
if (!quoted)
{
sb.AppendLine();
foreach (var e in Enumerable.Range(0, indent))
sb.Append(indentString);
}
break;
case ':':
sb.Append(ch);
if (!quoted)
sb.Append(" ");
break;
default:
sb.Append(ch);
break;
}
}
return sb.ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment