Developer Documentation
C#
Updated September 19, 2026

Format JSON in C#

Pretty-print JSON with predictable indentation and validation in C#.

Formatting JSON means parsing valid JSON and serializing it again with whitespace and indentation that make the structure easier to read. Parsing first also catches malformed input.

Quick Start#

The following example uses the standard C# API or a widely used package for this task.

Quick start#

C#
1using System.Text.Json;23using JsonDocument doc = JsonDocument.Parse(input);4string formatted = JsonSerializer.Serialize(5    doc.RootElement,6    new JsonSerializerOptions { WriteIndented = true }7);8Console.WriteLine(formatted);

Common Operations#

This second pattern covers a common production operation or a safer way to handle real input.

Validate while formatting#

C#
1try2{3    using JsonDocument doc = JsonDocument.Parse(input);4    string pretty = JsonSerializer.Serialize(doc.RootElement, new JsonSerializerOptions5    {6        WriteIndented = true7    });8}9catch (JsonException ex)10{11    Console.WriteLine($"Invalid JSON near line {ex.LineNumber}, byte {ex.BytePositionInLine}");12}

Important Notes#

Keep JsonDocument alive while reading its JsonElement values; clone elements if they need to outlive the document.

Best Practices#

  1. Treat external input as untrusted and handle parse/validation errors explicitly.
  2. Keep encoding, units, formats, and library-specific mapping rules explicit at system boundaries.
  3. Add test vectors that cover empty input, Unicode text, malformed input, and representative production data.

References#

Implement JSON Formatter in other languages: