Pretty Printing Unformatted Json In C#
[C#, .NET]
Occasionally, you will find yourself in a position where you have unformatted or poorly formatted JSON, and you would like to view it formatted, also known as pretty printed.
There are a bunch of online resources for this, such as this one, this one and this one
But writing a few lines of code to solve this problem is very trivial, using the types found in the System.Text.Json namespace.
The code will be as follows:
using System.Text.Json;
string json = """
{
"name": "James Bond","age": 45, "agency": "MI-6", "status":{ "retired":true, "code":"007"}
}
""";
var formattedJson = JsonNode.Parse(json);
Console.Write(formattedJson);
This will output the following:
{
"name": "James Bond",
"age": 45,
"agency": "MI-6",
"status": {
"retired": true,
"code": "007"
}
}
It is trivial to refactor this to accept the unformatted JSON as input and then wrap the code in a LinqPad script, a console application, or a WebAPI for routine access.
If you are using Newtonsoft.Json, the code is even simpler:
var formattedJson = JToken.Parse(json);
Console.Write(formattedJson);
Happy hacking!