GameParticles
Developer

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. // note and /* note */ are both errors.
  • Literals are lowercase: true, false, null. True, NULL and undefined are invalid.
  • Numbers cannot have leading zeros (007), a leading plus (+5), or be NaN or Infinity.
  • 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.

Tools in this guide

Frequently asked questions

Why does my JSON fail with Unexpected token at position N?

The parser reached a character it did not expect at that offset. Look one token before the position: a trailing comma, a single quote or a missing closing bracket is almost always the cause.

Are comments allowed in JSON?

No. Neither // nor /* */ is part of the JSON grammar. Some tools accept them in config files (JSONC, JSON5), but a standard parser such as JSON.parse will reject them.

Is formatting JSON the same as validating it?

Formatting re-indents valid JSON for readability. Validation checks the syntax. A formatter has to parse the text first, so it validates as a side effect, but it does not check your data against a schema.

How do I convert Python dict output into real JSON?

Use json.dumps(obj) in Python instead of str(obj). The str form uses single quotes and Python literals like True and None, which are not valid JSON.

More developer guides

JSON Formatter
Developer · Format, validate and minify JSON with syntax highlighting.
↵
Base64 Encode / Decode
Developer · Encode text to Base64 or decode Base64 back to plain text.
↵
URL Encoder / Decoder
Developer · Encode or decode URL components and query strings.
↵
Hash Generator
Developer · Generate MD5, SHA-1, SHA-256 and SHA-512 hashes.
↵
UUID Generator
Developer · Generate UUIDs v4 (random) in bulk with one click.
↵
Regex Tester
Developer · Test regular expressions against text with live match highlighting.
↵
Word Counter
Text · Count words, characters, sentences, paragraphs and reading time.
↵
Case Converter
Text · Convert text between UPPER, lower, Title, camelCase, snake_case and more.
↵
List Sorter
Text · Sort, reverse, deduplicate and shuffle lists of text.
↵
Markdown Preview
Text · Write Markdown and see a live rendered preview side by side.
↵
Percentage Calculator
Numbers · Calculate percentages, increases, decreases and what % one number is of another.
↵
Color Converter
Colors · Convert colors between HEX, RGB, HSL and HSV instantly.
↵
Snake
Arcade · Eat food, grow longer, don't hit the walls. A timeless classic.
↵
2048
Puzzle · Slide tiles and combine them to reach the legendary 2048 tile.
↵
Word Grid
Puzzle · Guess the hidden five letter word in six tries using color clues.
↵
Sudoku
Puzzle · Fill the 9x9 grid with logic. Four difficulties from easy to expert.
↵
Minesweeper
Strategy · Use number clues to clear the minefield. Classic logic, three levels.
↵
Breakout
Arcade · Smash every brick with paddle and ball. Power-ups, combos, endless levels.
↵
Typing Practice
Casual · Build your WPM and accuracy with timed drills from 30 seconds to 5 minutes. Find your weak keys.
↵
TypeRunner
Arcade · Multiplayer typing race. Race friends by link, beat computer runners, or chase your own ghost.
↵
Typing Blocks
Arcade · Type each word before its wooden block lands. Miss, and the pile climbs toward the line.
↵
Bubble Shooter
Arcade · Aim, bank shots off the walls, and pop groups of three or more bubbles.
↵
Road Rush
Arcade · Race seven rivals through traffic and punch your way to the front.
↵