Code reference: format, minify, and parse JSON in any language
The tool above prettifies, validates, and minifies JSON in your browser. The reference below shows the equivalent operations in the languages and tools you reach for when the paste-format-copy loop isn't where the work happens: server scripts, CI pipelines, database clients, and the shell. Fifteen languages plus six databases; copy-and-paste ready.
JavaScript / TypeScript
The browser and Node both ship the canonical implementation on the global JSON object. No imports needed.
// Pretty-print with 2-space indent
JSON.stringify(value, null, 2)
// Pretty-print with 4-space indent
JSON.stringify(value, null, 4)
// Pretty-print with tab indent
JSON.stringify(value, null, '\t')
// Minify (omit the third argument)
JSON.stringify(value)
// Parse string to object
JSON.parse(rawText)
// Pretty-print with sorted top-level keys
JSON.stringify(value, Object.keys(value).sort(), 2)The third argument to stringify is the indent: an integer (number of spaces, capped at 10) or a string used verbatim per level. The second argument is a replacer function or an array of allowed keys.
Scripting languages
| Language | Pretty-print | Minify | Parse |
|---|---|---|---|
| Python | json.dumps(d, indent=2) | json.dumps(d, separators=(',', ':')) | json.loads(s) |
| Python (file) | python -m json.tool < in.json | n/a | json.load(open('f.json')) |
| Ruby | JSON.pretty_generate(h) | JSON.generate(h) | JSON.parse(str) |
| PHP | json_encode($d, JSON_PRETTY_PRINT) | json_encode($d) | json_decode($s, true) |
| Perl | JSON::PP->new->pretty->encode($h) | JSON::PP->new->encode($h) | JSON::PP->new->decode($s) |
| Lua (dkjson) | dkjson.encode(t, {indent=true}) | dkjson.encode(t) | dkjson.decode(s) |
Python's default json.dumps(d) adds a space after : and ,. To produce wire-format minified output, pass separators=(',', ':'). PHP's JSON_PRETTY_PRINT uses 4-space indent and is not configurable through the flag.
Compiled and managed languages
| Language | Pretty-print | Minify | Parse |
|---|---|---|---|
| Go | json.MarshalIndent(v, "", " ") | json.Marshal(v) | json.Unmarshal(b, &v) |
| Rust (serde_json) | serde_json::to_string_pretty(&v) | serde_json::to_string(&v) | serde_json::from_str::<Value>(s) |
| Java (Jackson) | mapper.writerWithDefaultPrettyPrinter().writeValueAsString(o) | mapper.writeValueAsString(o) | mapper.readValue(s, T.class) |
| Java (Gson) | new GsonBuilder().setPrettyPrinting().create().toJson(o) | gson.toJson(o) | gson.fromJson(s, T.class) |
| C# (System.Text.Json) | JsonSerializer.Serialize(o, new JsonSerializerOptions { WriteIndented = true }) | JsonSerializer.Serialize(o) | JsonSerializer.Deserialize<T>(s) |
| C# (Newtonsoft) | JsonConvert.SerializeObject(o, Formatting.Indented) | JsonConvert.SerializeObject(o) | JsonConvert.DeserializeObject<T>(s) |
| Kotlin (kotlinx) | Json { prettyPrint = true }.encodeToString(v) | Json.encodeToString(v) | Json.decodeFromString<T>(s) |
| Swift | JSONEncoder().with { $0.outputFormatting = .prettyPrinted }.encode(v) | JSONEncoder().encode(v) | JSONDecoder().decode(T.self, from: d) |
Go's MarshalIndent defaults to no prefix and accepts any indent string. Jackson's default pretty printer uses 2-space indent. System.Text.Json indents with 2 spaces on .NET 6–8; .NET 9 added IndentCharacter and IndentSize properties for configurability.
Shell and CLI tools
| Tool | Pretty-print | Minify | Notes |
|---|---|---|---|
| jq | jq . file.json | jq -c . file.json | Defaults to 2-space indent |
| jq (custom indent) | jq --indent 4 . file.json | n/a | Accepts 0–7 |
| python -m json.tool | python -m json.tool < file.json | python -m json.tool --compact < file.json | Stdlib, no deps |
| node | node -e "console.log(JSON.stringify(JSON.parse(fs.readFileSync(0,'utf8')),null,2))" | node -e "console.log(JSON.stringify(JSON.parse(fs.readFileSync(0,'utf8'))))" | Reads stdin |
| yq | yq -P -o=json file.json | yq -o=json -I=0 file.json | Same author as jq |
| gron | gron file.json | gron -u file.json | Greppable line-per-key form |
| fx | cat file.json | fx | n/a | Interactive viewer |
jq is the de facto CLI for JSON. It defaults to 2-space indent with no key sorting; pass -S to sort keys alphabetically before output.
Databases
| Database | Pretty-print | Minify / parse |
|---|---|---|
| PostgreSQL | SELECT jsonb_pretty('{"a":1}'::jsonb); | '{"a":1}'::jsonb (parse + minify) |
| MySQL 5.7+ | SELECT JSON_PRETTY('{"a":1}'); | JSON_VALID('{"a":1}') |
| SQLite (JSON1) | n/a (use client) | SELECT json('{"a":1}'); |
| BigQuery | TO_JSON_STRING(JSON '{"a":1}', true) | TO_JSON_STRING(JSON '{"a":1}') |
| SQL Server 2016+ | FORMATMESSAGE workaround, or client-side | ISJSON(s) for validation |
| MongoDB shell | printjson(doc) | JSON.stringify(doc) |
SQLite's JSON1 extension intentionally has no JSON_PRETTY function. Format in your client. PostgreSQL jsonb_pretty reorders keys and removes duplicates because jsonb is a normalized binary representation; use json_pretty (no b) on a json column if you need to preserve input order.
JSON escape sequences (RFC 8259 §7)
| Escape | Character | Code point |
|---|---|---|
\" | Double quote | U+0022 |
\\ | Reverse solidus (backslash) | U+005C |
\/ | Solidus (forward slash, optional) | U+002F |
\b | Backspace | U+0008 |
\f | Form feed | U+000C |
\n | Line feed | U+000A |
\r | Carriage return | U+000D |
\t | Tab | U+0009 |
\u0000 to \uFFFF | Any BMP character by hex code point | U+0000 to U+FFFF |
\uD83D\uDE00 | UTF-16 surrogate pair (renders as 😀) | code points above U+FFFF |
The forward-slash escape (\/) is optional. Some producers emit it for safe embedding inside HTML <script> blocks, where the literal sequence </ could close the surrounding tag. Parsers accept it either way. Characters above U+FFFF must be written as two \uXXXX escapes forming a UTF-16 surrogate pair.
JSON variants and supersets
| Variant | Trailing commas | Comments | Unquoted keys | Single quotes | Common use |
|---|---|---|---|---|---|
| JSON (RFC 8259) | no | no | no | no | strict baseline; what jsonr accepts |
| JSON5 | yes | // and /* */ | yes | yes | hand-edited config |
| JSONC | yes | // and /* */ | no | no | VS Code settings, tsconfig.json |
| JSONL / NDJSON | n/a | no | no | no | line-per-record streaming logs |
| HJSON | yes | #, //, /* */ | yes | optional | human-friendly config |
| BSON | binary | binary | binary | binary | MongoDB wire format |
| JSON-LD | no | no | no | no | linked data with @context |
To format JSONC or JSON5 in jsonr, strip comments and trailing commas first. npx strip-json-comments-cli < file.jsonc handles JSONC. The json5 package (Python and Node) parses JSON5 into a value you can re-serialize as strict JSON.
Parser failure modes
| Symptom in the error bar | Cause | Fix |
|---|---|---|
Expected property name in JSON at position X | Trailing comma before } or ] | Remove the comma |
Expected double-quoted property name | Unquoted key ({name: ...}) | Wrap the key in "..." |
Unexpected token ' | Single-quoted string or key | Replace ' with " |
Unexpected token / | Comment in the input | Strip comments before pasting |
Unexpected token N | Literal NaN, Infinity, or undefined | Replace with null or remove the field |
Unexpected end of JSON input | Truncated input | Re-copy from the source; the paste likely cut off mid-buffer |
Unexpected non-whitespace character after JSON data | Two top-level values (NDJSON pasted as a single doc) | Wrap the lines in [ ... ] with commas between |
Bad escaped character | Invalid backslash sequence in a string | Use \uXXXX for arbitrary characters |
Unexpected token in JSON at position 0 | Empty input or BOM at start | Strip the byte-order mark; check for leading whitespace |
The browser's JSON.parse reports a byte offset; jsonr translates that offset into the line and column shown in the error bar by walking the input string up to the failure point.
Related concepts
- •JSON Schema: declarative validation language for JSON shape and content; spec at json-schema.org
- •JSON Pointer (RFC 6901): path syntax for addressing a value inside a JSON document
- •JSONPath and JMESPath: XPath-style query languages for JSON, used in jq plugins and the AWS/Azure CLIs
- •Canonical JSON (RFC 8785 JCS): deterministic serialization used when hashing or signing JSON
- •JSON Merge Patch (RFC 7396): diff-and-apply format for JSON documents over HTTP PATCH