Rick Strahl's Weblog  

Wind, waves, code and everything in between...
.NET • C# • Markdown • WPF • All Things Web
Contact   •   Articles   •   Products   •   Support   •   Advertise
Sponsored by:
West Wind WebSurge - Rest Client and Http Load Testing for Windows

Prettifying a JSON String in .NET


:P
On this page:

Here’s a quick and dirty tip if you’re dealing with JSON strings that you at times need to display for debugging or simply seeing a quick view of data represented. It may be that you have an application that captures HTTP responses and you need to actually decipher the JSON that was sent to you, or you’re creating a quick and dirty admin form where you just want to dump some settings information into a screen.

As is usually the case, JSON.NET makes JSON manipulations super easy – in fact it’s a single line of code:

string jsonFormatted = JValue.Parse(json).ToString(Formatting.Indented);

Here’s how you can test this out:

[TestMethod]
public void PrettifyJsonStringTest()
{
    var test = new
    {
        name = "rick",
        company = "Westwind",
        entered = DateTime.UtcNow
    };

    string json = JsonConvert.SerializeObject(test);
    Console.WriteLine(json); // single line JSON string
           
    string jsonFormatted = JValue.Parse(json).ToString(Formatting.Indented);
            
    Console.WriteLine(jsonFormatted);
}

The code above of course is contrived as SerializeObject() also supports the Formatting.Indented option. But assume for a second that you are getting data already in string format from somewhere such as an HTTP stream or a file on disk. You then use the above code to convert into something much more readable.

In practice, it’s nice if you have any interfaces that need to display JSON in the UI. For example in West Wind Web Surge I display sent and captured HTTP content and if the result is JSON the default Raw Response output looks like this:

WebSurgeRaw

Workable but not exactly readable.

By applying formatting it sure is a lot easier to see what the JSON actually looks like:

WebSurgeFormattedJson

Likewise if you’re dealing with objects that have .ToString() methods that return JSON (as many online SDKs do!), it’s nice to have an easy way to format the result into something more readable that you can dump into the Debug console.

It’s simple solution to a not so often required problem, but I’ve run into this enough times when I forgot exactly which JSON.NET object is required to handle this, so I wrote it down for next time for me to remember and maybe this might be useful to some of you as well.

this post created and published with Markdown Monster
Posted in .NET  C#  

The Voices of Reason


 

Dan
July 06, 2016

# re: Prettifying a JSON String in .NET

After you formatted the JSON response, how did you do syntax highlighting?

Rick Strahl
July 06, 2016

# re: Prettifying a JSON String in .NET

Easiest probably to use highlight.js. Above in West Wind WebSurge I'm using AceEditor.js.

Johan
January 05, 2022

# re: Prettifying a JSON String in .NET

Hi Rick, just made great use of this pretty printer, excellent/thanks.

You still surf Kanaha Lowers? Remember you from when I lived in Kula back in the nineties /Aloha from Goteborg, Sweden 😃


Serhan
January 12, 2022

# re: Prettifying a JSON String in .NET

Hey Rick.

Data integrity is crucial for debugging scenarios and unfortunately this method causes data loss in some cases.

Test your solution with the following two JSON.

/*Json.NET respects me!*/{"foo":"bar"}
{"p":"1","p":"2","p":"3"}

I would stick with less-fancy but more reliable JsonTextWriter.WriteToken(JsonReader).


Matthew
January 19, 2022

# re: Prettifying a JSON String in .NET

I've been assigned to a project involving a lot of JSON and I keep coming back to this. Thanks!


Rick Strahl
January 26, 2022

# re: Prettifying a JSON String in .NET

@Serhan - neither of these are valid JSON. Comments aren't officially supported in JSON and most parsers will just ignore the comments. Many others will outright fail on comments. Duplicate keys are also not valid for JavaScript/JSON and are consolidated into a single value. How would you even reference these duplicate keys?

Garbage in Garbage out.


Noe
July 22, 2022

# re: Prettifying a JSON String in .NET

This is exactly what I was looking for to simply print Azure SDK responses. Thanks!


West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2024