Last active
February 27, 2020 15:17
-
-
Save TylerBrinkley/3b47f07622c0c38e472565aa76ff778f to your computer and use it in GitHub Desktop.
Json Prettifier and Minifier
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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