JSON Prettifier

This is a simple class I wrote to nicely format a JSON string. Just call it with JsonFormatter.PrettyPrint(yourJsonString)

public static class JsonFormatter
{
    public static string Indent = "    ";

    public static void AppendIndent(StringBuilder sb, int count)
    {
        for (; count > 0; --count) sb.Append(Indent);
    }

    public static bool IsEscaped(StringBuilder sb, int index)
    {
        bool escaped = false;
        while (index > 0 && sb[--index] == '\\') escaped = !escaped;
        return escaped;
    }

    public static string PrettyPrint(string input)
    {
        var output = new StringBuilder(input.Length * 2);
        char? quote = null;
        int depth = 0;

        for(int i=0; i<input.Length; ++i)
        {
            char ch = input[i];

            switch (ch)
            {
                case '{':
                case '[':
                    output.Append(ch);
                    if (!quote.HasValue)
                    {
                        output.AppendLine();
                        AppendIndent(output, ++depth);
                    }
                    break;
                case '}':
                case ']':
                    if (quote.HasValue)  
                        output.Append(ch);
                    else
                    {
                        output.AppendLine();
                        AppendIndent(output, --depth);
                        output.Append(ch);
                    }
                    break;
                case '"':
                case '\'':
                    output.Append(ch);
                    if (quote.HasValue)
                    {
                        if (!IsEscaped(output, i))
                            quote = null;
                    }
                    else quote = ch;
                    break;
                case ',':
                    output.Append(ch);
                    if (!quote.HasValue)
                    {
                        output.AppendLine();
                        AppendIndent(output, depth);
                    }
                    break;
                case ':':
                    if (quote.HasValue) output.Append(ch);
                    else output.Append(" : ");
                    break;
                default:
                    if (quote.HasValue || !char.IsWhiteSpace(ch))
                        output.Append(ch);
                    break;
            }
        }

        return output.ToString();
    }
}
Posted in

8 thoughts on “JSON Prettifier

  1. Hi – Thank you for posting this code; I am indeed looking for a way to get PHP to prettify its json_encode() output… can you tell me where to put this code of yours? I have never used any “public static class” stuff before, and my parser seems not to like it… I have it right after the opening <?php and the parser says "syntax error, unexpected T_PUBLIC in /webroot/ke4x.json.php on line 2". Got any ideas what I'm doing wrong?

    Thank you –

  2. Yes, I guess I should have made it more clear, but that’s C# code. You won’t be able to get it to work in a PHP application.

    If you just need to format some JSON for a one-time thing, you can try one these online beautifiers: http://jsonformat.com/ or http://jsonformatter.curiousconcept.com/

    If need to do it programatically in PHP, then I’m afraid you’re on your own. You can try searching for a PHP solution, or write your own. The C# I wrote should be fairly legible and easy to follow, you could base your code on that if you wanted to.

  3. @luis: Glad it worked for you. Looking over this again though, I think there’s a little bug. I don’t check the quote type, so I think you can close a double quote with a single quote.

  4. @Mark : I’ll try that. At first I had trouble reading in data, quotes are part of my JSON string. Then, I as able to pass in the data via a file.

    var jsontxt = System.IO.File.ReadAllText(@”C:\Users\\json.txt”);
    System.Console.WriteLine( JsonFormatter.PrettyPrint(jsontxt) ); // Worked

  5. opps… :/

    var jsontxt = System.IO.File.ReadAllText(@”C:\Users\\gson.txt”);

  6. oh.. wp ate the brackets in my directory name parameter. Basically, pass in the directory location of the file 😉

  7. Thanks for the code. This comes in handy.
    Reading JSON is really painful especially when it comes as a big glob of text. If you are debugging and need to quickly prettify a JSON string you can try this online json formatter: http://www.onlinejsonformatter.com/
    You can copy and paste your JSON string or enter a URL that returns JSON string. Bonus feature is you can even convert your JSON to XML.

Leave a Reply

Your email address will not be published. Required fields are marked *