Skip to content

Instantly share code, notes, and snippets.

@TylerBrinkley
Last active February 27, 2020 15:17
Show Gist options
  • Save TylerBrinkley/3b47f07622c0c38e472565aa76ff778f to your computer and use it in GitHub Desktop.
Save TylerBrinkley/3b47f07622c0c38e472565aa76ff778f to your computer and use it in GitHub Desktop.
Json Prettifier and Minifier
public static string Prettify(string json)
{
var sb = new StringBuilder(json.Length * 2);
var indent = 0;
var startOfLine = false;
for (var i = 0; i < json.Length; ++i)
{
var c = json[i];
if (!char.IsWhiteSpace(c))
{
var nextIsStartOfLine = false;
switch (c)
{
case '}':
case ']':
--indent;
startOfLine = true;
nextIsStartOfLine = true;
break;
case ',':
startOfLine = false;
nextIsStartOfLine = true;
break;
}
if (startOfLine)
{
sb.AppendLine()
.Append(' ', Math.Max(indent * 2, 0));
startOfLine = false;
}
sb.Append(c);
switch (c)
{
case '{':
case '[':
++indent;
startOfLine = true;
break;
case '\"':
c = '_'; // throw-away value
var escape = false;
while (i + 1 < json.Length && (escape || c != '\"'))
{
escape = c == '\\' ? !escape : false;
sb.Append(c = json[++i]);
}
break;
case ':':
sb.Append(' ');
break;
default:
startOfLine = nextIsStartOfLine;
break;
}
}
}
return sb.ToString();
}
public static string Minify(string json)
{
var sb = new StringBuilder(json.Length);
for (var i = 0; i < json.Length; ++i)
{
var c = json[i];
if (!char.IsWhiteSpace(c))
{
sb.Append(c);
if (c == '\"')
{
c = '_'; // throw-away value
var escape = false;
while (i + 1 < json.Length && (escape || c != '\"'))
{
escape = c == '\\' ? !escape : false;
sb.Append(c = json[++i]);
}
}
}
}
return sb.ToString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment