Formatting Json data in a MVC View

A quick tip on how to prettify Json data when displaying it in a .Net Core MVC view.

In the controller add a reference to the following;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

Then use the following to format the Json data:

ViewBag.JsonData = JValue.Parse(data).ToString(Formatting.Indented);

Finally in the view, output the data using the HTML.Raw and enclosing it tags:


This will give the following output (based on the standard Bootstrap theme that is used in default .Net Core project template):


Alex Orpwood Written by:

Software developing and architecting for 20 years. Satellite monitoring by day, writing my own app by night. More about me