Skip to content

Instantly share code, notes, and snippets.

@gsscoder
Last active March 25, 2021 07:36
Show Gist options
  • Save gsscoder/16a47b5785de76dc5a3805fce811cf9a to your computer and use it in GitHub Desktop.
Save gsscoder/16a47b5785de76dc5a3805fce811cf9a to your computer and use it in GitHub Desktop.
C# helper method to pretty print JSON (ILogger friendly)
// 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