Skip to content

Instantly share code, notes, and snippets.

@c272
Last active April 29, 2019 20:59
Show Gist options
  • Save c272/b2d17373fd3d4ff40c1fc4ed7d9ca3ec to your computer and use it in GitHub Desktop.
Save c272/b2d17373fd3d4ff40c1fc4ed7d9ca3ec to your computer and use it in GitHub Desktop.
Simple JSON pretty printing in C#, as a string extension.
public static class StringExtensions {
//Returns the string, if JSON, as a pretty printed string.
public static string PrettyPrint(this string d)
{
IList<string> actionLines = d.SplitAndKeepDelimiters('{', '}', ',');
string s = "";
//Write per line, leave space between each action.
int tabDepth = 0;
for (int i = 0; i < actionLines.Count; i++)
{
//Modifying tab depth for removal.
if (actionLines[i] == "}") { tabDepth--; }
//Adding tab depth.
s += new string(' ', tabDepth * 4);
//Adding text contents.
s += actionLines[i];
//Checking if a line ending is required.
if (i != actionLines.Count - 1 && actionLines[i + 1] != ",")
{
s += "\r\n";
}
//Modifying tab depth for addition.
if (actionLines[i] == "{") { tabDepth++; }
}
return s;
}
//You also need this, but you can replace this with Regex if you want. Just less performant.
public static IList<string> SplitAndKeepDelimiters(this string s, params char[] delimiters)
{
var parts = new List<string>();
if (!string.IsNullOrEmpty(s))
{
int iFirst = 0;
do
{
int iLast = s.IndexOfAny(delimiters, iFirst);
if (iLast >= 0)
{
if (iLast > iFirst)
parts.Add(s.Substring(iFirst, iLast - iFirst)); //part before the delimiter
parts.Add(new string(s[iLast], 1));//the delimiter
iFirst = iLast + 1;
continue;
}
//No delimiters were found, but at least one character remains. Add the rest and stop.
parts.Add(s.Substring(iFirst, s.Length - iFirst));
break;
} while (iFirst < s.Length);
}
return parts;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment