Last active
September 25, 2015 02:17
-
-
Save kamranayub/846861 to your computer and use it in GitHub Desktop.
Formats a valid JSON string into a pretty output
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
/// <summary> | |
/// Formats a JSON string by walking through it and examining the contents. | |
/// </summary> | |
/// <param name="json">Unformatted JSON string, expects valid JSON with quoted keys and no whitespace.</param> | |
/// <returns>Formatted JSON string</returns> | |
/// <remarks> | |
/// [ { should have line breaks and tabs after them | |
/// ] } should have line breaks and tabs before them | |
/// : should have a space after it | |
/// , should have a line break and tab | |
/// </remarks> | |
public static string PrettyJson(this string json) | |
{ | |
var sbOutput = new StringBuilder(); | |
bool inQuotes = false; | |
int level = 0; | |
Action Tabify = () => | |
{ | |
var chars = new char[level]; | |
for (var i = 0; i < level; i++) | |
chars[i] = '\t'; | |
sbOutput.Append(chars); | |
}; | |
for (var i = 0; i < json.Length; i++) | |
{ | |
var curChar = json[i]; | |
// Ignore escaped quotes | |
if (curChar == '"' && json[i - 1] != '\\') | |
{ | |
if (!inQuotes) | |
inQuotes = true; | |
else | |
inQuotes = false; | |
} | |
// Don't format anything within quotes | |
if (!inQuotes) | |
{ | |
if (curChar == '{' || curChar == '[' || curChar == ',') | |
{ | |
if (curChar != ',') level++; | |
sbOutput.Append(curChar); | |
sbOutput.AppendLine(); | |
Tabify(); | |
} | |
else if (curChar == '}' || curChar == ']') | |
{ | |
level--; | |
sbOutput.AppendLine(); | |
Tabify(); | |
sbOutput.Append(curChar); | |
} | |
else if (curChar == ':') | |
{ | |
sbOutput.Append(curChar + " "); | |
} | |
else | |
{ | |
sbOutput.Append(curChar); | |
} | |
} | |
else | |
{ | |
sbOutput.Append(curChar); | |
} | |
} | |
return sbOutput.ToString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment