Programming  /  C# April 07, 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(
    @"(¤(\\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.

PS. For updates about new posts, sites I find useful and the occasional rant you can follow me on Twitter. You are also most welcome to subscribe to the RSS-feed.

Joel Abrahamsson

Joel Abrahamsson

I'm a passionate web developer and systems architect living in Stockholm, Sweden. I work as CTO for a large media site and enjoy developing with all technologies, especially .NET, Node.js, and ElasticSearch. Read more


comments powered by Disqus

More about C#