Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.