BBuildQuill
How-To Guides9 min read

How to Format, Validate, and Debug JSON: A Complete Guide

A practical, in-depth guide to reading, formatting, validating, and debugging JSON. Covers syntax rules, common errors, and workflows developers use daily.

JSON is everywhere. Every API you call, every config file you edit, and every package.json you touch speaks it. Yet a single misplaced comma can break a deployment, and a deeply nested response can hide the one field you need behind a wall of brackets.

This guide covers the full workflow: reading JSON with confidence, formatting it so humans can work with it, validating it before it breaks something, and debugging the errors that validators throw at you. By the end, you should be able to fix almost any broken JSON document in minutes.

What JSON Actually Is

JSON stands for JavaScript Object Notation. Douglas Crockford specified it in the early 2000s as a lightweight way to exchange data between systems. It won because it is simple. The entire grammar fits on a business card.

JSON has exactly six value types:

  • Object: an unordered set of key-value pairs wrapped in curly braces, like {"name": "Sara"}
  • Array: an ordered list of values wrapped in square brackets, like [1, 2, 3]
  • String: text wrapped in double quotes
  • Number: integer or decimal, no quotes
  • Boolean: true or false, no quotes
  • Null: the literal null

That is the whole language. Everything else, including dates, binary data, and comments, has to be represented using these six types or left out entirely. Most JSON bugs come from developers assuming JSON supports something it does not.

The Syntax Rules That Trip People Up

JSON looks like JavaScript, and that resemblance causes most errors. JavaScript is forgiving. JSON is not. Here are the rules that differ from what your instincts might tell you:

  1. Keys must be double-quoted. {name: "Sara"} is valid JavaScript but invalid JSON. It must be {"name": "Sara"}.
  2. Strings use double quotes only. 'single quotes' are a syntax error.
  3. No trailing commas. [1, 2, 3,] fails. The last item in any array or object must not be followed by a comma.
  4. No comments. There is no // or /* */ in JSON. If you need to annotate, add a key like "_comment".
  5. No undefined, NaN, or Infinity. These are JavaScript values, not JSON values. Use null or a string instead.
  6. Numbers cannot have leading zeros. 007 is invalid. Write 7, or quote it as a string if the zeros matter.
  7. Special characters in strings must be escaped. A literal double quote inside a string becomes \", a backslash becomes \\, and a newline becomes \n.

Keep this list nearby. When a validator reports an error, the cause is almost always one of these seven rules.

Step 1: Format the JSON So You Can Read It

Machine-generated JSON usually arrives minified: a single line with no spaces, sometimes hundreds of kilobytes long. The first step in any JSON task is making it readable.

Formatting, also called pretty-printing, adds line breaks and indentation that reflect the structure. Each nesting level gets indented, usually by two or four spaces. A minified blob like this:

{"user":{"id":42,"roles":["admin","editor"],"active":true}}

becomes this:

{
  "user": {
    "id": 42,
    "roles": ["admin", "editor"],
    "active": true
  }
}

Nothing about the data changed. Whitespace outside of strings has no meaning in JSON, so formatting is always safe.

You have several options for formatting:

  • An online formatter. Paste your JSON into our JSON Formatter, and it formats and validates in one step, entirely in your browser.
  • Your editor. VS Code formats JSON with Shift+Alt+F. Most editors have an equivalent.
  • The command line. python -m json.tool file.json or jq . file.json both pretty-print.
  • In code. JSON.stringify(data, null, 2) in JavaScript produces two-space indented output.

For exploring large documents, a tree viewer beats flat text. Our JSON Viewer renders the document as a collapsible tree, so you can fold away the parts you do not care about and drill into the parts you do.

Step 2: Validate Before You Use It

Validation answers one question: is this document legal JSON? A validator parses the text with a strict grammar and reports the first place the text breaks the rules, usually with a line and column number.

Always validate in these situations:

  • Before committing config files. A broken JSON config often fails at deploy time, which is the most expensive time to find out.
  • After hand-editing. Humans introduce trailing commas and mismatched brackets. Machines do not.
  • After concatenating or templating JSON. String-building JSON is error-prone. If you generate JSON by joining strings, validate the result every time.
  • When an API rejects your request. A 400 response with a vague message often means malformed JSON in the request body.

A subtle point about validators: they stop at the first error. If your document has five problems, you will fix them one at a time, revalidating after each fix. That is normal. Do not assume one green run means the document was only broken in one place you already knew about.

Reading Error Messages Correctly

Validator errors look cryptic until you learn their dialect. Here are the most common messages and what they actually mean:

"Unexpected token } in JSON at position 41". The parser hit a closing brace it was not expecting. Nine times out of ten, the previous line ends with a trailing comma. Position numbers count characters from the start of the document, so paste the JSON into a formatter to convert that position into something you can see.

"Unexpected end of JSON input". The document stopped before the structure was complete. You are missing at least one closing brace or bracket, or the text was truncated during copy-paste. Check whether the last character is the closer you expect.

"Unexpected token ' in JSON". Single quotes. Replace them with double quotes.

"Unexpected token N". Usually NaN leaked into the output from the code that generated the JSON. Similarly, "Unexpected token u" is often the string undefined appearing where a value should be.

"Bad control character in string literal". There is a raw newline or tab inside a string. Inside JSON strings, those must be written as \n and \t.

The general technique: find the position the error points to, then look just before it. Parsers report where they gave up, but the actual mistake is usually a few characters earlier.

The Debugging Workflow, Start to Finish

When you face a broken or confusing JSON document, work through these steps in order:

1. Pretty-print it first

Even if the document is invalid, most formatters will show you the structure up to the error point. Structure makes every following step easier.

2. Check the brackets balance

Every { needs a }, and every [ needs a ]. Editors highlight matching pairs when you place the cursor on a bracket. For a large document, collapse sections in a tree viewer and watch for the section that will not collapse cleanly.

3. Hunt the seven syntax rules

Scan for trailing commas, single quotes, unquoted keys, comments, and raw special characters. These cause the overwhelming majority of failures.

4. Isolate by bisection

For a large document that fails somewhere in the middle, delete half the document and validate again. If it passes, the error is in the half you removed. Keep halving until the error is cornered in a few lines. This sounds crude, but it is fast and it always works.

5. Compare against a known-good version

If a config worked yesterday and fails today, diff the two versions. Our JSON Diff compares two documents structurally, so it catches changes in values and structure even when the formatting differs.

6. Extract just the part you need

When the document is valid but enormous, you rarely need all of it. A JSONPath query like $.data.items[0].price pulls out a specific value directly. You can test queries interactively with our JSON Path Tester.

Common Real-World Scenarios

The API response that will not parse

You call an API, pass the body to JSON.parse, and get an exception. Before blaming your code, look at the raw response. APIs sometimes return HTML error pages with a 200 status code, and HTML starting with < is the classic "Unexpected token <" error. The fix belongs in your error handling, not in your JSON.

The config file that breaks after editing

You added one entry to a JSON config and now the app will not start. You almost certainly introduced a trailing comma or forgot a comma between the old last entry and your new one. Both mistakes live on the same line you edited, so this one is quick to find once you know to look.

The escaped-JSON-inside-JSON puzzle

Some systems store JSON as a string inside another JSON document. It arrives looking like "{\"level\":\"deep\"}". To read it, you unescape and parse twice: parse the outer document, take the string value, and parse that string as JSON again. Formatters cannot see into the inner document until you unwrap it.

Duplicate keys behaving strangely

{"a": 1, "a": 2} is technically parseable, and most parsers silently keep the last value. If a value seems to change mysteriously, search the document for the key name and check whether it appears twice at the same level.

Handling Large JSON Files

Documents beyond a few megabytes need different tactics:

  • Do not open them in a basic text editor. Use a tree viewer or a streaming tool. Browser-based tools that process locally, like the BuildQuill viewers, handle multi-megabyte files fine because nothing is uploaded.
  • Minify for transfer, format for reading. Whitespace can double file size. Keep stored and transmitted JSON minified and format on demand.
  • Query instead of scrolling. JSONPath or jq filters find the needle without you reading the haystack.
  • Watch number precision. JSON numbers beyond 2^53 lose precision in JavaScript. IDs from databases often exceed this. If you see IDs ending in 000 that should not, the producer needs to send them as strings.

A Note on JSON Security

Two habits keep you safe. First, never build JSON by concatenating strings with untrusted input; use your language's serializer, which handles escaping correctly. Second, never paste sensitive production data into random online tools. Prefer tools that process in the browser without uploading, and for anything regulated, use offline tools only.

Quick Reference: Valid JSON Checklist

Before you save or send a JSON document, run through this list:

  1. All keys double-quoted
  2. All strings double-quoted
  3. No trailing commas
  4. No comments
  5. Brackets and braces balanced
  6. No undefined, NaN, or Infinity
  7. Special characters escaped inside strings
  8. File encoded as UTF-8 without a byte order mark

Wrapping Up

JSON debugging stops being frustrating once you internalize two things: the grammar is tiny, and errors cluster around the same seven mistakes. Format first, validate early, read error positions carefully, and bisect when lost.

The tools mentioned in this guide, including the JSON Formatter, JSON Viewer, JSON Diff, and JSON Path Tester, all run locally in your browser, so you can debug real payloads without your data leaving your machine.