ProgrammingApril 7, 2012

Syntax highlighting JSON with C#

A not so simple C# method that makes JSON look pretty.

Here’s something I’d like to never do again. I recently needed to process a string containing JSON to make it suitable for displaying in a HTML document. I managed to have it indented fairly quickly thanks to JSON.NET (I already had it as a JObject on which I invoked ToString(Formatting.Indented).

But having it syntax highlighted proved to be harder. Luckily I found this question on Stack Overflow linking to this snippet of JavaScript code. After contemplating not porting it to C# for an hour or two I finally sat down and did it.

I’m sure it could be done in a more efficient and readable way, but this seems to work:

public string SyntaxHighlightJson(string original)
{
  return Regex.Replace(
    original,
    @"(¤(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\¤])*¤(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)".Replace('¤', '"'),
    match => {
      var cls = "number";
      if (Regex.IsMatch(match.Value, @"^¤".Replace('¤', '"'))) {
        if (Regex.IsMatch(match.Value, ":$")) {
          cls = "key";
        } else {
          cls = "string";
        }
      } else if (Regex.IsMatch(match.Value, "true|false")) {
        cls = "boolean";
      } else if (Regex.IsMatch(match.Value, "null")) {
        cls = "null";
      }
      return "<span class=\"" + cls + "\">" + match + "</span>";
    });
}

Displaying the output of this method in a pre tag and adding some colors to the classes .string, .number, .boolean, .null and .key it produces a decent looking and fairly readable result.

Tagsjson