public
Last active

Formats a valid JSON string into a pretty output

  • Download Gist
JsonPretty.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
/// <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();
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.