Skip to content

Getting Started

m4bwav edited this page Sep 30, 2026 · 4 revisions

Install

In a project directory:

dotnet add package JsonPrettyPrinter

Or add the reference to the project file yourself:

<PackageReference Include="JsonPrettyPrinter" Version="3.0.2" />

In Visual Studio's Package Manager Console:

Install-Package JsonPrettyPrinter

The package targets netstandard2.0 and net10.0, so it works on .NET Framework 4.6.2 and later, .NET Core, .NET 5 and later, and Mono. The download is 37 KB. The net10.0 build has no dependencies. The netstandard2.0 build depends on System.Memory and System.Text.Json, which NuGet adds for you; the FAQ lists what comes with them.

The first call

Everything is in the namespace JsonPrettyPrinterPlus; the serialisation helpers are in JsonPrettyPrinterPlus.JsonSerialization. The examples on this wiki use C# 11 raw string literals ("""...""") so the JSON reads as JSON. On an older compiler, write @"{""a"":1}" or "{\"a\":1}" instead.

using System;
using JsonPrettyPrinterPlus;

var json = """{"name":"Ada","tags":["math","engines"],"born":1815,"empty":{}}""";
Console.WriteLine(json.PrettyPrintJson());

prints

{
    "name": "Ada",
    "tags": [
        "math",
        "engines"
    ],
    "born": 1815,
    "empty": {}
}

Every value goes on its own line, indented four spaces per level, with one space after each colon. Empty objects and arrays stay on one line. Lines end with a line feed on every operating system. Whitespace outside strings is discarded first, so input that is already formatted, or oddly spaced, comes out the same way, and pretty printing twice gives the same text. Output format has every rule.

Changing the layout

JsonPrettyPrintOptions sets the indent and the line terminator.

var two = json.PrettyPrintJson(new JsonPrettyPrintOptions { IndentSize = 2 });
var tabs = json.PrettyPrintJson(new JsonPrettyPrintOptions { UseTabs = true });
var crlf = json.PrettyPrintJson(new JsonPrettyPrintOptions { NewLine = Environment.NewLine });

The defaults are IndentSize = 4, UseTabs = false and NewLine = "\n". IndentSize = 0 keeps one value per line with no indentation. The record is immutable, so keep one instance and reuse it, or derive one with JsonPrettyPrintOptions.Default with { IndentSize = 2 }.

A printer object

The extension method is enough for most code. JsonPrettyPrinter is for reusing one set of options, or for writing straight to a stream:

using System.IO;

var printer = new JsonPrettyPrinter(new JsonPrettyPrintOptions { IndentSize = 2 });

string pretty = printer.PrettyPrint(json);           // a string
printer.PrettyPrint(json, Console.Out);              // straight into any TextWriter

using (var file = File.CreateText("pretty.json"))
    printer.PrettyPrint(json, file);                 // no second string for a large document

A printer is not thread-safe; make one per thread, or use PrettyPrintJson(), which keeps one per thread for you.

Serialising an object

using JsonPrettyPrinterPlus.JsonSerialization;

var thing = new { Name = "Mark", Tags = new[] { "a", "b" }, When = new DateTime(2010, 1, 1), Price = 9.5m };
Console.WriteLine(thing.ToJson(prettyPrint: true));
{
    "Name": "Mark",
    "Tags": [
        "a",
        "b"
    ],
    "When": "2010-01-01T00:00:00",
    "Price": 9.5
}

DeserializeFromJson<T>() goes the other way. Serialisation helpers covers serializer options, camel case, escaping, source generation and native AOT.

A script instead of a project

A .NET 10 file-based app needs one line for the package:

#:package JsonPrettyPrinter@3.0.2
using System;
using JsonPrettyPrinterPlus;

Console.WriteLine("""{"a":[1,2],"b":{}}""".PrettyPrintJson());
dotnet run pretty.cs

If the script also calls ToJson() or DeserializeFromJson<T>() without a JsonTypeInfo, add #:property PublishAot=false under the package line. File-based apps enable native AOT by default, and that turns off reflection-based System.Text.Json, so the call throws InvalidOperationException ("Reflection-based serialization has been disabled for this application"). The printer itself is unaffected.

F# Interactive:

#r "nuget: JsonPrettyPrinter, 3.0.2"
open JsonPrettyPrinterPlus
open JsonPrettyPrinterPlus.JsonSerialization

let json = """{"a":[1,{"b":"c"}],"e":{}}"""
printfn "%s" (json.PrettyPrintJson())
printfn "%s" (json.PrettyPrintJson(JsonPrettyPrintOptions(IndentSize = 2)))
printfn "%s" ({| Name = "Ada"; Tags = [| "math" |] |}.ToJson(prettyPrint = true))

PowerShell 7 can load the assembly straight from the NuGet cache. The cache holds it once any project on the machine has restored the package; otherwise download the .nupkg from nuget.org and unzip it.

Add-Type -Path "$env:USERPROFILE/.nuget/packages/jsonprettyprinter/3.0.2/lib/netstandard2.0/JsonPrettyPrinterPlus.dll"
[JsonPrettyPrinterPlus.PrettyPrinterExtensions]::PrettyPrintJson('{"a":[1,2],"b":{}}')

$options = [JsonPrettyPrinterPlus.JsonPrettyPrintOptions]::new()
$options.IndentSize = 2
[JsonPrettyPrinterPlus.PrettyPrinterExtensions]::PrettyPrintJson('{"a":[1]}', $options)

$compact = [ordered]@{ name = 'Ada'; tags = @('math') } | ConvertTo-Json -Compress
[JsonPrettyPrinterPlus.PrettyPrinterExtensions]::PrettyPrintJson($compact)

Tested with PowerShell 7.6 on .NET 10, where System.Memory and System.Text.Json are part of the runtime. Windows PowerShell 5.1 runs on .NET Framework and was not tested.

Unity

Not tested by the maintainer. The netstandard2.0 build is the one to use. It needs System.Memory at run time even for pretty printing alone (the printer works on ReadOnlySpan<char>), and System.Text.Json with its dependencies for the serialisation helpers. A NuGet-for-Unity tool brings those in; copying only JsonPrettyPrinterPlus.dll into Assets/Plugins is not enough. If you try it, an issue with the result helps the next person.

Characters outside ASCII

The printer copies them through unchanged: {"café":"naïve ☕ 😀 日本"} comes out as written. If a Windows console shows question marks, set the console encoding first:

Console.OutputEncoding = System.Text.Encoding.UTF8;

ToJson() is different: System.Text.Json escapes non-ASCII characters and a few ASCII ones by default. Serialisation helpers says how to relax that.

Next: Recipes for working patterns, or the API reference for every member.

Clone this wiki locally