using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace prettycode.org
{
public static class JsonFormatter
{
public static string JsCasePropertyNames(string json)
{
var buffer = new StringBuilder();
var inString = false;
for (var i = 0; i < json.Length; i++)
{
var currentChar = json[i];
char? previousChar = (i > 0) ? (char?)json[i - 1] : null;
if (currentChar == '"' && previousChar.HasValue && previousChar != '\\')
{
inString = !inString;
}
if (inString && currentChar == '"' && "{,".Contains(previousChar.Value))
{
buffer.Append("\"" + Char.ToLowerInvariant(json[++i]));
}
else
{
buffer.Append(currentChar);
}
}
return buffer.ToString();
}
public static string PrettyPrint(string json, string indent = " ")
{
var buffer = new StringBuilder();
var depth = 0;
var inString = false;
for (var i = 0; i < json.Length; i++)
{
var currentChar = json[i];
if (currentChar == '"' && i > 0 && json[i - 1] != '\\')
{
inString = !inString;
}
if (inString)
{
buffer.Append(currentChar);
}
else if (currentChar == '{' || currentChar == '[')
{
buffer.Append(currentChar + "\n" + string.Concat(Enumerable.Repeat(indent, ++depth)));
}
else if (currentChar == '}' || currentChar == ']')
{
buffer.Append("\n" + string.Concat(Enumerable.Repeat(indent, --depth)) + currentChar);
}
else if (currentChar == ',')
{
buffer.Append(",\n" + string.Concat(Enumerable.Repeat(indent, depth)));
}
else if (currentChar == ':')
{
buffer.Append(": ");
}
else
{
buffer.Append(currentChar);
}
}
return buffer.ToString();
}
}
}