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.
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.
Similar articles
- Inversion of Control – It’s broader than just injecting components
- A neat little type inference trick with C#
- Getting property and method names using static reflection in C#
- Detecting mouse and keyboard input with .NET
- Creating a custom Configuration Section in .NET
- Learning Scala part six – If statements and Loops
- Invoking methods based on a parameter without if-else statements in C#
- Learning Scala part five - Methods

Comments
comments powered by Disqus