Skip to content

How to validate and pretty-print JSON in your language

Real snippets to validate JSON and produce readable output (pretty print). Includes dependencies when the language has no built-in JSON.

← Developer Zone
Updated: 2026-03-22

Use this article when...

This section is built for speed: one concrete task, multiple stacks, and the minimum context needed not to copy the wrong thing.

Use this after capturing the real payload

Work from the request or response body that actually failed instead of rebuilding JSON from memory.

Pick the language that matches the incident

The useful path here is fast adaptation: choose your stack, then copy only after reading the notes around parsing and formatting.

Validate the result with the tool

Once the snippet runs, inspect the live payload with JSON Formatter or the related tool to confirm the structure is really fixed.

What this article gives you

A short path from incident to implementation: context, language-specific snippets, and the warning signs that usually get skipped.

Languages

13

Related tools

3

Topics

json, debugging, api, formatting

When debugging APIs, logs, or configs, the issue is rarely “JSON or not JSON”, but “unreadable JSON” or “invalid JSON”. The goal is a fast routine: parse, fail with a clear error, and produce formatted output to read or share.

This guide gives short, real snippets to validate and pretty-print JSON. For strict production validation, consider JSON Schema in your stack.

Dependency snapshot by language

Check this first to see which snippets use built-in/runtime APIs and which ones need external packages before you start copying code.

Bash
External

jq.

C#
Built-in

Built-in or runtime API

Delphi
Check notes

Review the notes for setup details.

Go
Check notes

Review the notes for setup details.

Java
External

com.fasterxml.jackson.core:jackson-databind.

JavaScript
Built-in

Built-in or runtime API

Kotlin
External

jackson-databind.

PHP
Check notes

Review the notes for setup details.

Python
Built-in

Built-in or runtime API

Ruby
Built-in

Built-in or runtime API

Rust
External

serde = { version = "1", features = ["derive"] }, serde_json = "1".

TypeScript
Built-in

Built-in or runtime API

VB.NET
Built-in

Built-in or runtime API

How to use these code examples well

The snippet is only the fast path. The explanation and notes are what keep you from copying the wrong assumption into production.

1. Start with the problem

Make sure the article really matches the issue you are debugging before copying code just because the title looks close.

2. Read the notes

That is where portability limits, dependency requirements, and runtime assumptions usually appear.

3. Validate the output

If the code runs but the bug remains, jump to the related tool and inspect the real payload, token, timestamp, or config.

Code examples by language

Snippets that compile/run, plus short explanations and real-world notes.

Bash

bash
Bash
echo "{"a":1,"b":[2,3]}" | jq .
Explanation

jq validates and pretty-prints JSON. If the input is invalid, jq exits with a useful error and a non-zero status code.

Notes
  • Dependency: jq.
  • Great for pipelines (curl | jq).

C#

csharp
C#
using System;
using System.Text.Json;

var input = "{\"a\":1,\"b\":[2,3]}";
using var doc = JsonDocument.Parse(input);
var pretty = JsonSerializer.Serialize(doc, new JsonSerializerOptions { WriteIndented = true });
Console.WriteLine(pretty);
Explanation

JsonDocument.Parse validates JSON. If it is valid, JsonSerializer can re-serialize with WriteIndented to produce consistent pretty output.

Notes
  • System.Text.Json (std).
  • Do not assume key ordering is preserved (JSON does not guarantee it).

Delphi

delphi
Delphi
program JsonValidate;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  System.JSON;

var
  V: TJSONValue;

begin
  V := TJSONObject.ParseJSONValue('{"a":1,"b":[2,3]}');
  try
    if not Assigned(V) then
      raise Exception.Create('Invalid JSON');
    Writeln(V.ToString);
  finally
    V.Free;
  end;
end.
Explanation

ParseJSONValue works as a fast validation step: if it returns nil, the JSON is invalid. ToString returns a normalized representation (not necessarily pretty).

Notes
  • Std: System.JSON.
  • If you need pretty print, you typically use a third-party formatter or custom formatting.

Go

go
Go
package main

import (
  "bytes"
  "encoding/json"
  "fmt"
)

func main() {
  input := []byte(`{"a":1,"b":[2,3]}`)
  var out bytes.Buffer
  if err := json.Indent(&out, input, "", "  "); err != nil {
    panic(err)
  }
  fmt.Println(out.String())
}
Explanation

json.Indent validates JSON and rewrites it with indentation. It is great for CLIs and services when you need readable logs.

Notes
  • Std: encoding/json.
  • To validate without formatting, use json.Valid(input).

Java

java
Java
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
  public static void main(String[] args) throws Exception {
    var mapper = new ObjectMapper();
    Object obj = mapper.readValue("{\"a\":1,\"b\":[2,3]}", Object.class);
    System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj));
  }
}
Explanation

Java SE does not include JSON as a standard library. With Jackson you can parse and re-serialize with a pretty printer.

Notes
  • Dependency: com.fasterxml.jackson.core:jackson-databind.
  • In backend, catch JsonProcessingException for clear errors.

JavaScript

javascript
JavaScript
const input = "{\"a\":1,\"b\":[2,3]}";
const obj = JSON.parse(input);
console.log(JSON.stringify(obj, null, 2));
Explanation

JSON.parse validates strict JSON syntax. JSON.stringify with indentation produces readable output for debugging and tickets.

Notes
  • Std.
  • Note: JSON.parse validates syntax, not schema.

Kotlin

kotlin
Kotlin
import com.fasterxml.jackson.databind.ObjectMapper

fun main() {
  val mapper = ObjectMapper()
  val obj: Any = mapper.readValue("{\"a\":1,\"b\":[2,3]}", Any::class.java)
  println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj))
}
Explanation

In Kotlin/JVM, a practical approach is to reuse Jackson to parse and pretty-print JSON.

Notes
  • Dependency: jackson-databind.
  • Alternative: kotlinx.serialization (also a dependency).

PHP

php
PHP
<?php
$input = "{\"a\":1,\"b\":[2,3]}";
$data = json_decode($input, true, 512, JSON_THROW_ON_ERROR);
echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . PHP_EOL;
Explanation

json_decode with JSON_THROW_ON_ERROR gives clear errors when JSON is invalid. json_encode with JSON_PRETTY_PRINT generates readable output.

Notes
  • Requires JSON_THROW_ON_ERROR (PHP 7.3+).
  • If you must preserve big integers, review options and types.

Python

python
Python
import json

s = "{\"a\":1,\"b\":[2,3]}"
obj = json.loads(s)
print(json.dumps(obj, indent=2, ensure_ascii=False))
Explanation

json.loads validates and parses. json.dumps with indent produces pretty output ready to paste in tickets.

Notes
  • Std.
  • If you need stable diffs, use sort_keys=True, but do not treat it as a contract.

Ruby

ruby
Ruby
require "json"

s = "{\"a\":1,\"b\":[2,3]}"
obj = JSON.parse(s)
puts JSON.pretty_generate(obj)
Explanation

JSON.parse validates and parses. JSON.pretty_generate produces a formatted version useful for debugging.

Notes
  • Std.
  • If you parse big numbers, review Integer/Float conversions.

Rust

rust
Rust
use serde_json::Value;

fn main() {
  let input = r#"{"a":1,"b":[2,3]}"#;
  let v: Value = serde_json::from_str(input).unwrap();
  println!("{}", serde_json::to_string_pretty(&v).unwrap());
}
Explanation

serde_json lets you parse and pretty-print JSON safely and quickly. It is the de facto standard in Rust.

Notes
  • Dependency: serde = { version = "1", features = ["derive"] }, serde_json = "1".

TypeScript

ts
TypeScript
const input = "{\"a\":1,\"b\":[2,3]}";
const obj = JSON.parse(input) as unknown;
console.log(JSON.stringify(obj, null, 2));
Explanation

In TS, JSON.parse can be treated as unknown for strictness. The parse + stringify(…, null, 2) pattern is still great for quick pretty output.

Notes
  • Std.
  • If you must validate shape, add runtime validation (zod/io-ts) or schema validation in backend.

VB.NET

vbnet
VB.NET
Imports System
Imports System.Text.Json

Module Program
  Sub Main()
    Dim input = "{""a"":1,""b"":[2,3]}"
    Using doc As JsonDocument = JsonDocument.Parse(input)
      Dim pretty = JsonSerializer.Serialize(doc, New JsonSerializerOptions With {.WriteIndented = True})
      Console.WriteLine(pretty)
    End Using
  End Sub
End Module
Explanation

In VB.NET (same as C#), System.Text.Json lets you validate and re-serialize with indentation.

Notes
  • System.Text.Json (std).

Related tools

Use the tool when you need to generate or validate output fast.

Trust and privacy

Copy/paste-friendly by design. Still, treat real production secrets carefully.

  • Prefer synthetic examples when sharing screens or recording.
  • Do not paste real API keys, tokens, or personal data unless you fully trust your environment.
  • If you need ordering, do not use UUID v4 as a sortable id: add createdAt or use sortable ids.