I apologize for asking this question in this manner, but I evidently don't have enough "Reputation" to post a question as a comment in the originating thread.
Someone here made a nice little class to properly indent a JSON string so it's more human-friendly. It works great, except that I'd like to modify it so that empty arrays are represented by "[]" rather than having a bunch of whitespace between the characters (newline, likely several indent characters, etc.). It seemed like such a simple plan.
The original code looks like this:
private const string INDENT_STRING = " ";
public static string FormatJson(string str)
{
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;
}
}
return sb.ToString();
}
I tried modifying it so it had this in it:
case '[':
sb.Append(ch);
if (!quoted)
{
if (str[i + 1] != ']')
{
sb.AppendLine();
Enumerable.Range(0, ++indent).ForEach(item => sb.Append(INDENT_STRING));
}
}
break;
It blows up on me, complaining that I'm referencing an index that's too large (actually, it complains about something that has a number of possibilities, 'ArgumentOutOfRangeException'
being the most likely). I tried adding a tracker to see if i+1 > str.Length
, but it still blows up. And the spot in the string it's blowing up at isn't anywhere near a [
or a ]
. Indeed, ch
is a '{' and str[i+1]
is a ','.
Am I making any sense?
I thought about just taking the resulting string and using Regex to rip out any whitespace between [ and ], but that seemed inelegant.
Does anyone have a recommendation for how to modify this otherwise-excellent code to be the way I want? I tried, really I did...