Skip to content

Instantly share code, notes, and snippets.

@kamranayub
Last active September 25, 2015 02:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamranayub/846861 to your computer and use it in GitHub Desktop.
Save kamranayub/846861 to your computer and use it in GitHub Desktop.
Formats a valid JSON string into a pretty output
/// <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