Skip to content

Instantly share code, notes, and snippets.

@jrgcubano
Created March 24, 2015 08:45
Show Gist options
  • Save jrgcubano/bf0b28fc87ebefec6af3 to your computer and use it in GitHub Desktop.
Save jrgcubano/bf0b28fc87ebefec6af3 to your computer and use it in GitHub Desktop.
FormatJsonString
public static class JsonFormatHelper
{
private const string INDENT_STRING = " ";
public static string FormatJson(string str)
{
//if(ConfigHelper.GetAppSetting<bool>("Console", false))
return FormatStrJson(str);
//return String.Empty;
}
public static string FormatStrJson(string str)
{
if (str != null)
{
var indent = 0;
var quoted = false;
var sb = new StringBuilder();
for (var i = 0; i < str.Length; i++)
{
var ch = str[i];
switch (ch)
{
case '{':
case '[':
sb.Append(ch);
if (!quoted)
{
sb.AppendLine();
Enumerable.Range(0, ++indent).ForEach(item => sb.Append(INDENT_STRING));
}
break;
case '}':
case ']':
if (!quoted)
{
sb.AppendLine();
Enumerable.Range(0, --indent).ForEach(item => sb.Append(INDENT_STRING));
}
sb.Append(ch);
break;
case '"':
sb.Append(ch);
bool escaped = false;
var index = i;
while (index > 0 && str[--index] == '\\')
escaped = !escaped;
if (!escaped)
quoted = !quoted;
break;
case ',':
sb.Append(ch);
if (!quoted)
{
sb.AppendLine();
Enumerable.Range(0, indent).ForEach(item => sb.Append(INDENT_STRING));
}
break;
case ':':
sb.Append(ch);
if (!quoted)
sb.Append(" ");
break;
default:
sb.Append(ch);
break;
}
}
// Fix (remove database laststamp and sequential fields from sb)
string input = sb.ToString();
string regex = "(\\s{4}\"laststamp\".*\n.*\n.*\n.*\n.*\n.*\n.*\n.*\n.*\n.*\\].*\n\\s*)|(\"sequential\".*\n\\s*)";
string output = Regex.Replace(input, regex, "");
return output;
}
return String.Empty;
}
}
static class Extensions
{
public static void ForEach<T>(this IEnumerable<T> ie, Action<T> action)
{
foreach (var i in ie)
{
action(i);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment