How to Format and Validate JSON (and Fix Common Errors)
Learn how to format, validate and minify JSON, read parser error messages, and fix the usual culprits: trailing commas, single quotes and unescaped text.
Updated
Formatting JSON means re-indenting it so each key sits on its own line; validating means checking it follows the JSON grammar exactly. Paste the text into a formatter, read the first error it reports, fix that one thing, and run it again. Most broken JSON has one of about six mistakes, and all of them are listed below.
What valid JSON actually requires
JSON is stricter than JavaScript object literals, which is where most confusion starts. The rules that matter:
- Keys must be strings in double quotes:
{"a":1}is valid,{a:1}and{'a':1}are not. - String values use double quotes only.
"it's"is fine;'single'is not. - No trailing commas.
[1,2,3,]fails;[1,2,3]passes. - No comments.
// noteand/* note */are both errors. - Literals are lowercase:
true,false,null.True,NULLandundefinedare invalid. - Numbers cannot have leading zeros (
007), a leading plus (+5), or beNaNorInfinity. - The top level can be any value, but most APIs expect an object
{}or an array[].
If you keep these seven rules in mind you can usually spot the problem by eye. When you cannot, a validator gives you the exact position.
How to read a parser error
Every JSON parser reports the position where it gave up, not necessarily where the mistake is. Unexpected token } in JSON at position 42 means the parser reached a } when it expected something else, typically because the previous line ends with a trailing comma. Unexpected end of JSON input means a bracket or quote was opened and never closed. Unexpected token ' almost always means single quotes.
The practical approach: look at the reported position, then look one token backwards. The JSON Formatter flags the error inline at that position in the text, so you do not have to count characters yourself.
Fixing the common errors
Trailing commas
Copying from JavaScript, Python dicts or hand-edited config files leaves a comma after the last item. Delete the comma before each } and ]. Linters allow it in JS; JSON never does.
Single quotes and unquoted keys
Python's print(dict) output, {'name': 'Ada', 'age': 36}, looks like JSON but is not. Replace ' with " and quote any bare keys. If the source is Python, use json.dumps() instead of str() to get real JSON.
Unescaped characters inside strings
A literal double quote or newline inside a string must be escaped: "She said \"hi\"" and "line one\nline two". Backslashes themselves become \\, so a Windows path is "C:\\Users\\ada". Tabs are \t, and any Unicode code point can be written as \u00e9.
Encoding and invisible characters
A byte order mark at the start of a file, smart quotes pasted from a document, or a non-breaking space between tokens all produce confusing errors on what looks like a clean line. Retype the suspicious quotes, and save the file as UTF-8 without BOM.
Concatenated or wrapped documents
Log files often contain one JSON object per line. That whole file is not valid JSON; each line is. Split on newlines and parse each line separately, or wrap the lines in [ and ] with commas between them. Likewise, an API response wrapped in a callback like cb({...}) is JSONP, so strip the function call first.
Pretty-print versus minify
Pretty-printed JSON uses two or four spaces per nesting level and one key per line, which is what you want for reading, diffs and config files committed to git. Minified JSON strips all whitespace into one line, which is what you want on the wire or inside an environment variable. Both are the same data. JSON.stringify(obj, null, 2) pretty-prints in JavaScript; JSON.stringify(obj) minifies. In Python, json.dumps(obj, indent=2) does the same job.
Formatting never changes meaning, but key order is not guaranteed by the JSON spec. Do not write code that depends on {"b":1,"a":2} staying in that order after a round trip.Validating against a schema
Syntax validation only tells you the text is well-formed JSON. It does not tell you that "age" is a number or that "email" is present. For that you need JSON Schema, with a validator such as Ajv in JavaScript or jsonschema in Python. Start with syntax, because a schema validator cannot run on text that does not parse.
Converting to and from other formats
Spreadsheets want rows and columns, not nested objects. An array of flat objects such as [{"id":1,"name":"Ada"},{"id":2,"name":"Lin"}] maps cleanly to CSV with a header row, and the JSON to CSV converter handles quoted fields and embedded commas in both directions. Nested objects need to be flattened first.
Config files for Kubernetes, GitHub Actions and Docker Compose are usually YAML. Every JSON document is also valid YAML, but the reverse is not true, since YAML allows comments, anchors and unquoted strings. When a YAML file misbehaves, converting it with the YAML to JSON converter shows you exactly how the parser interpreted each value, which catches the classic surprise of yes becoming true or 3.10 becoming 3.1.
The rest of the format, encode and validate tools live in the developer category.
Try it
Paste your failing JSON into the JSON Formatter. It runs in your browser, highlights the error at the exact position, and lets you switch between pretty and minified output with a custom indent width.