Last active
March 25, 2021 07:36
-
-
Save gsscoder/16a47b5785de76dc5a3805fce811cf9a to your computer and use it in GitHub Desktop.
C# helper method to pretty print JSON (ILogger friendly)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// based on: https://gist.github.com/FrankHu-MSFT/b6750185b19fd4ada4ba36b099985813 | |
// can removes \r to fit in a single log line when using ILogger | |
using System.IO; | |
using Newtonsoft.Json; | |
static class JsonUtil | |
{ | |
public static string Prettify(string json, bool stripLineFeed = false) | |
{ | |
using var stringReader = new StringReader(json); | |
using var stringWriter = new StringWriter(); | |
var jsonReader = new JsonTextReader(stringReader); | |
var jsonWriter = new JsonTextWriter(stringWriter) { Formatting = Formatting.Indented }; | |
jsonWriter.WriteToken(jsonReader); | |
var prettified = stringWriter.ToString(); | |
return stripLineFeed switch { | |
true => prettified.Replace("\r", string.Empty), | |
_ => prettified | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment