G-19 · Developer · 5 min read

How to format and validate JSON (and fix common errors)

Pretty-print and validate JSON, fix trailing commas, single quotes and comments that break parsers, then generate TypeScript types from a sample.

Updated Uses JSON Formatter, JSON to TypeScript
Fig. G-19 · Developer

Minified JSON from an API or a log is hard to read, and one misplaced comma makes the whole document unusable. Formatting shows its structure at a glance, and a strict parser tells you exactly where it breaks. This guide covers both, explains the most common errors and their fixes, and finishes by turning a JSON sample into TypeScript types.

Step by step

  1. Open the JSON formatter and paste your JSON into the input box.
  2. Leave the mode on Format and pick an indent: 2 spaces, 4 spaces or a tab. Tick Sort keys if you want object keys in alphabetical order, which makes two documents easier to compare.
  3. If the JSON is valid, the formatted result appears below. Copy it or download it.
  4. If it is invalid, read the error message. It comes from the browser's own JSON parser, and when the parser reports a character position the tool converts it into a line and column so you can jump straight to the problem.
  5. Fix the problem in the input and the result updates. Repeat until it parses.
  6. To send the JSON somewhere compact, switch the mode to Minify, which strips all optional whitespace.

Everything happens in your browser, so internal data is never sent to a server.

What "valid JSON" actually means

JSON is defined by RFC 8259 and ECMA-404, and it is stricter than the JavaScript object syntax it resembles. A valid document follows these rules:

  • Strings and object keys use double quotes. 'name' and bare name are not allowed.
  • No comma after the last item in an object or array.
  • No comments of any kind, neither // nor /* */.
  • Values are limited to strings, numbers, objects, arrays, true, false and null. undefined, NaN, Infinity, dates and functions do not exist in JSON.
  • Numbers are written in decimal without leading zeros (07 is invalid) and without a leading +.
  • Control characters inside strings, such as a literal tab or newline, must be escaped as \t or \n.

The formatter applies these rules exactly, as the standard requires. That is deliberate: if it accepted a trailing comma, you would ship JSON that a stricter parser in production then rejects.

Fixing the most common JSON errors

Most broken JSON comes from hand editing, copying a JavaScript object, or a configuration format that allows extras. Here is a typical example that fails:

{
  // user record
  'id': 42,
  name: "Ada",
  "tags": ["admin", "editor",],
}

It has four problems: a comment, single-quoted key, an unquoted key and two trailing commas. The corrected version:

{
  "id": 42,
  "name": "Ada",
  "tags": ["admin", "editor"]
}
Symptom Likely cause Fix
Error just before a } or ] Trailing comma Delete the comma after the last item
Error at a ' Single quotes Replace with double quotes, and escape any " inside the string as \"
Error at a letter at the start of a key Unquoted key Wrap the key in double quotes
Error at a / Comment Remove the comment or move the note into a field
Error at the very end Missing closing } or ] Count brackets, or format the part that parses to see where nesting stops
Error inside a long string Unescaped newline, tab or " Escape it as \n, \t or \"

Exact error wording varies between browsers. Chrome and Edge typically say something like "Unexpected token" or "Expected double-quoted property name", followed by a position. Firefox reports a line and column itself. Either way, look a character or two before the reported spot: the parser often only notices the problem at the next token.

Tip If you need to find a specific error in a large file, a find and replace with the regular expression ,\s*([\]}]) and the replacement $1 removes trailing commas in one pass. Check the result, because the same pattern would also change a string that happens to contain ", ]".

When the file is not meant to be JSON

Some formats look like JSON but intentionally allow more. tsconfig.json and VS Code settings use JSONC, which permits comments and trailing commas. JSON5 also allows single quotes and unquoted keys. A strict validator will reject these files, and that is correct: they are not JSON. Format them with an editor that understands their dialect, or strip the extras first if you need standard JSON for another tool.

Two things formatting can change

Formatting is meant to be lossless, but two edge cases are worth knowing.

Large numbers. The browser parses numbers as 64-bit floating point, which represents integers exactly only up to 2^53 (9,007,199,254,740,992). An ID such as 12345678901234567890 will come back slightly different after formatting. If your data contains very large integer IDs, keep them as strings in the JSON.

Key order. With Sort keys on, keys inside every object are reordered alphabetically. The data is the same, and array order is never changed, but if a consumer relies on key order (it should not, though some do), leave sorting off.

Duplicate keys are another quiet change: JSON parsers in browsers keep the last value for a repeated key, so {"a": 1, "a": 2} formats as {"a": 2}.

Generating TypeScript types from a sample

Once you have valid JSON, you can describe its shape in TypeScript instead of writing interfaces by hand. Paste the sample into the JSON to TypeScript tool, set the root type name, choose interface or type, and optionally tick export or readonly.

Given this sample:

{
  "id": 42,
  "name": "Ada",
  "tags": ["admin"],
  "orders": [
    { "id": 1, "total": 9.5 },
    { "id": 2, "total": 12, "coupon": "WELCOME" }
  ]
}

the tool produces:

export interface Root {
  id: number;
  name: string;
  tags: string[];
  orders: Order[];
}

export interface Order {
  id: number;
  total: number;
  coupon?: string;
}

The nested array of objects becomes its own Order interface, named from the key in singular form, and coupon is optional because only one of the two orders has it.

Types are inferred from the sample only, so the quality of the sample matters. A field that is null in the sample is typed as null, and an empty array becomes unknown[]. Use a response that shows every field with a real value, and include several array items if some fields are optional. Then adjust by hand where you know more than the sample does, such as a string that is really a union of a few allowed values.

If the JSON you are inspecting came from a token, the JWT decoder shows the decoded payload directly; for Base64 blobs inside JSON fields, use the Base64 decoder.

FAQ

Common questions.

01Why does my JSON fail with "Unexpected token"?

The parser met a character that is not allowed at that point. The usual causes are a trailing comma, single quotes, an unquoted key or a comment. Look at the reported line and column and the character just before it.

02Does formatting change my data?

No, apart from whitespace. Values and array order stay the same. The exceptions are integers beyond 2^53, which lose precision, duplicate keys, where only the last value survives, and key order if you choose Sort keys.

03Is it safe to paste private JSON into the formatter?

Yes. Parsing and formatting run in your browser and the text is never uploaded. You can confirm this by disconnecting from the network once the page has loaded; the tool keeps working.