sp
inputwaiting
1
outputempty
1
nothing yet...
{

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

LanguagePretty-printMinifyParse
Pythonjson.dumps(d, indent=2)json.dumps(d, separators=(',', ':'))json.loads(s)
Python (file)python -m json.tool < in.jsonn/ajson.load(open('f.json'))
RubyJSON.pretty_generate(h)JSON.generate(h)JSON.parse(str)
PHPjson_encode($d, JSON_PRETTY_PRINT)json_encode($d)json_decode($s, true)
PerlJSON::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

LanguagePretty-printMinifyParse
Gojson.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)
SwiftJSONEncoder().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

ToolPretty-printMinifyNotes
jqjq . file.jsonjq -c . file.jsonDefaults to 2-space indent
jq (custom indent)jq --indent 4 . file.jsonn/aAccepts 0–7
python -m json.toolpython -m json.tool < file.jsonpython -m json.tool --compact < file.jsonStdlib, no deps
nodenode -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
yqyq -P -o=json file.jsonyq -o=json -I=0 file.jsonSame author as jq
grongron file.jsongron -u file.jsonGreppable line-per-key form
fxcat file.json | fxn/aInteractive 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

DatabasePretty-printMinify / parse
PostgreSQLSELECT 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}');
BigQueryTO_JSON_STRING(JSON '{"a":1}', true)TO_JSON_STRING(JSON '{"a":1}')
SQL Server 2016+FORMATMESSAGE workaround, or client-sideISJSON(s) for validation
MongoDB shellprintjson(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)

EscapeCharacterCode point
\"Double quoteU+0022
\\Reverse solidus (backslash)U+005C
\/Solidus (forward slash, optional)U+002F
\bBackspaceU+0008
\fForm feedU+000C
\nLine feedU+000A
\rCarriage returnU+000D
\tTabU+0009
\u0000 to \uFFFFAny BMP character by hex code pointU+0000 to U+FFFF
\uD83D\uDE00UTF-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

VariantTrailing commasCommentsUnquoted keysSingle quotesCommon use
JSON (RFC 8259)nonononostrict baseline; what jsonr accepts
JSON5yes// and /* */yesyeshand-edited config
JSONCyes// and /* */nonoVS Code settings, tsconfig.json
JSONL / NDJSONn/anononoline-per-record streaming logs
HJSONyes#, //, /* */yesoptionalhuman-friendly config
BSONbinarybinarybinarybinaryMongoDB wire format
JSON-LDnonononolinked 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 barCauseFix
Expected property name in JSON at position XTrailing comma before } or ]Remove the comma
Expected double-quoted property nameUnquoted key ({name: ...})Wrap the key in "..."
Unexpected token 'Single-quoted string or keyReplace ' with "
Unexpected token /Comment in the inputStrip comments before pasting
Unexpected token NLiteral NaN, Infinity, or undefinedReplace with null or remove the field
Unexpected end of JSON inputTruncated inputRe-copy from the source; the paste likely cut off mid-buffer
Unexpected non-whitespace character after JSON dataTwo top-level values (NDJSON pasted as a single doc)Wrap the lines in [ ... ] with commas between
Bad escaped characterInvalid backslash sequence in a stringUse \uXXXX for arbitrary characters
Unexpected token in JSON at position 0Empty input or BOM at startStrip 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