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.
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.
Work from the request or response body that actually failed instead of rebuilding JSON from memory.
The useful path here is fast adaptation: choose your stack, then copy only after reading the notes around parsing and formatting.
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.
13
3
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.
jq.
Built-in or runtime API
Review the notes for setup details.
Review the notes for setup details.
com.fasterxml.jackson.core:jackson-databind.
Built-in or runtime API
jackson-databind.
Review the notes for setup details.
Built-in or runtime API
Built-in or runtime API
serde = { version = "1", features = ["derive"] }, serde_json = "1".
Built-in or runtime API
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.
Make sure the article really matches the issue you are debugging before copying code just because the title looks close.
That is where portability limits, dependency requirements, and runtime assumptions usually appear.
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
echo "{"a":1,"b":[2,3]}" | jq .
jq validates and pretty-prints JSON. If the input is invalid, jq exits with a useful error and a non-zero status code.
- Dependency: jq.
- Great for pipelines (curl | jq).
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);
JsonDocument.Parse validates JSON. If it is valid, JsonSerializer can re-serialize with WriteIndented to produce consistent pretty output.
- System.Text.Json (std).
- Do not assume key ordering is preserved (JSON does not guarantee it).
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.
ParseJSONValue works as a fast validation step: if it returns nil, the JSON is invalid. ToString returns a normalized representation (not necessarily pretty).
- Std: System.JSON.
- If you need pretty print, you typically use a third-party formatter or custom formatting.
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())
}
json.Indent validates JSON and rewrites it with indentation. It is great for CLIs and services when you need readable logs.
- Std: encoding/json.
- To validate without formatting, use json.Valid(input).
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));
}
}
Java SE does not include JSON as a standard library. With Jackson you can parse and re-serialize with a pretty printer.
- Dependency: com.fasterxml.jackson.core:jackson-databind.
- In backend, catch JsonProcessingException for clear errors.
JavaScript
const input = "{\"a\":1,\"b\":[2,3]}";
const obj = JSON.parse(input);
console.log(JSON.stringify(obj, null, 2));
JSON.parse validates strict JSON syntax. JSON.stringify with indentation produces readable output for debugging and tickets.
- Std.
- Note: JSON.parse validates syntax, not schema.
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))
}
In Kotlin/JVM, a practical approach is to reuse Jackson to parse and pretty-print JSON.
- Dependency: jackson-databind.
- Alternative: kotlinx.serialization (also a dependency).
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;
json_decode with JSON_THROW_ON_ERROR gives clear errors when JSON is invalid. json_encode with JSON_PRETTY_PRINT generates readable output.
- Requires JSON_THROW_ON_ERROR (PHP 7.3+).
- If you must preserve big integers, review options and types.
Python
import json
s = "{\"a\":1,\"b\":[2,3]}"
obj = json.loads(s)
print(json.dumps(obj, indent=2, ensure_ascii=False))
json.loads validates and parses. json.dumps with indent produces pretty output ready to paste in tickets.
- Std.
- If you need stable diffs, use sort_keys=True, but do not treat it as a contract.
Ruby
require "json"
s = "{\"a\":1,\"b\":[2,3]}"
obj = JSON.parse(s)
puts JSON.pretty_generate(obj)
JSON.parse validates and parses. JSON.pretty_generate produces a formatted version useful for debugging.
- Std.
- If you parse big numbers, review Integer/Float conversions.
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());
}
serde_json lets you parse and pretty-print JSON safely and quickly. It is the de facto standard in Rust.
- Dependency: serde = { version = "1", features = ["derive"] }, serde_json = "1".
TypeScript
const input = "{\"a\":1,\"b\":[2,3]}";
const obj = JSON.parse(input) as unknown;
console.log(JSON.stringify(obj, null, 2));
In TS, JSON.parse can be treated as unknown for strictness. The parse + stringify(…, null, 2) pattern is still great for quick pretty output.
- Std.
- If you must validate shape, add runtime validation (zod/io-ts) or schema validation in backend.
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
In VB.NET (same as C#), System.Text.Json lets you validate and re-serialize with indentation.
- 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.