Why JSON Doesn't Allow Comments (JSONC vs JSON5 Explained)

Why JSON Doesn't Allow Comments (JSONC vs JSON5 Explained)

Short answer: the JSON grammar has no comment syntax. RFC 8259 defines exactly six value types — object, array, string, number, boolean, and null — and its grammar for a JSON text contains no production for a comment. A conforming parser reaches a / and stops. That is the entire reason.

But the useful question is rarely "why". It is: my file has comments, my parser is failing, what now? The honest answer is that your file is not strict JSON. It is JSONC or JSON5, you are handing it to a strict parser, and the obvious fix — deleting the comments — is the step most likely to silently corrupt your data.

Tip: Automatically detect and fix errors in your JSON using the JSON Fix Tool. Fully client-side and secure—your data never leaves your browser.

Why the spec left comments out

The grammar has no slot for them

Comments are not a rule JSON relaxes. They are a feature that was never in the grammar. RFC 8259 models a document as a single value built from strings, numbers, literals, objects, and arrays. No production allows // or /* to begin a valid document, so "comments are not permitted in JSON" is a direct consequence of the grammar rather than a conservative restriction. The What Is JSON glossary entry covers the type system in full.

JSON is a wire format, not a config format

The pragmatic argument matters as much as the formal one. JSON was designed for implementations that shared no language, runtime, or error-handling model. Every shortcut a language designer might want — line comments, trailing commas, unquoted keys — produces a document one parser accepts and another silently misreads. A comment a server strips and a client keeps is a divergence, not a convenience.

The comment-free grammar gives a JSON document exactly one reading. That predictability is why JSON became the default for configuration, API payloads, and caches, while YAML took the opposite tradeoff and still pays for it in indentation errors.

The three families: strict JSON, JSONC, and JSON5

Once strict JSON is the baseline, everything else is a deliberate widening of the grammar.

Feature JSON (RFC 8259) JSONC JSON5
// and /* */ comments No Yes Yes
Trailing commas No Yes, in practice Yes
Unquoted object keys No No Yes
Single-quoted strings No No Yes
Hex, leading/trailing decimal point, leading + No No Yes
Infinity, NaN, -Infinity No No Yes
Multi-line strings via trailing backslash No No Yes
Parsed by JSON.parse Yes No No

Two distinctions here are routinely blurred:

JSONC is a convention, not a standard. It is Microsoft's terminology, and the de-facto reference implementation is jsonc-parser, the parser VS Code itself uses. No IETF document defines it, which is exactly why tools disagree about what "JSONC" permits.

JSON5 is a separate specification, published independently of JSON. It is not "JSONC with more features" — it is a different format that also happens to accept comments. A JSON5 parser is not automatically a JSONC parser, and vice versa. Treat them as two dialects, not a ladder.

The files you already have that are really JSONC

All of these are read with a comment-tolerant parser as a matter of tooling convention, not because JSON permits comments:

  • tsconfig.json — read by the TypeScript compiler through a JSONC parser
  • .vscode/settings.json — workspace settings
  • .vscode/launch.json — debugger configuration
  • .vscode/tasks.json — task runner configuration
  • keybindings.json — key bindings

The .json extension is historical. Nothing about the format changed.

The trailing-comma trap

Here is the part that bites. jsonc-parser tolerates not only comments but trailing commas, by default, in several of its parse configurations. So "JSONC" is not one stable dialect; it is a family of tolerances that vary by consumer.

Concretely: write a tsconfig.json with a trailing comma, save it, and VS Code reports zero problems. Every other surface is strict. Importing that file from Node.js throws SyntaxError: Unexpected token '}'. Your editor is not validating the file your runtime reads.

The rule that follows: an editor showing no errors is not evidence of valid JSON. It is evidence that the editor's dialect accepts it.

⚠️ The stripping hazard: a regex will corrupt valid JSON

Stripping the comments is the right instinct. It is almost always implemented wrongly.

// The reflexive fix. Do not ship this.
const stripped = text.replace(/\/\/.*$/gm, "");

The pattern assumes // outside a string means comment. That assumption is false, because // is a perfectly legal sequence inside a JSON string value:

{
  "url": "https://example.com/api",
  "note": "see // docs"
}

Both lines get truncated. The URL loses everything from // onward, and the note loses its closing quote and the rest of the object. The result is not merely invalid JSON — it is broken text that a repair pass will then mangle further. A sneakier variant: a document containing a URL and a real comment elsewhere can strip into something that still parses while now holding the wrong values.

This matters because string contents are data. URLs, regular expressions pasted into config, and prose notes all legitimately contain //. A correct stripper must track string literals and escape sequences, not just characters.

A stripper that is actually string-aware

function stripJsonComments(text) {
  let out = "";
  let inString = false;
  let inLineComment = false;
  let inBlockComment = false;
  let escaped = false;
 
  for (let i = 0; i < text.length; i++) {
    const ch = text[i];
    const next = text[i + 1];
 
    if (inLineComment) {
      if (ch === "\n") {
        inLineComment = false;
        out += ch;
      }
      continue;
    }
 
    if (inBlockComment) {
      if (ch === "*" && next === "/") {
        inBlockComment = false;
        i++;
      }
      continue;
    }
 
    if (inString) {
      out += ch;
      if (escaped) escaped = false;
      else if (ch === "\\") escaped = true;
      else if (ch === '"') inString = false;
      continue;
    }
 
    if (ch === '"') {
      inString = true;
      out += ch;
      continue;
    }
 
    if (ch === "/" && next === "/") {
      inLineComment = true;
      i++;
      continue;
    }
 
    if (ch === "/" && next === "*") {
      inBlockComment = true;
      i++;
      continue;
    }
 
    out += ch;
  }
 
  return out;
}

The idea is a single pass with a small state machine in which "am I inside a string?" is settled before "does this slash start a comment?". Anything that tokenizes first and discards comment tokens inherits the same correctness, which is why a token-aware repair library is right here and a regex is wrong.

How to get valid JSON out of a comment-laden file

  1. Check whether it is already strict JSON. Run it through the JSON Validator, which checks syntax only. If it parses, stop.
  2. Decide between fixing the source and stripping at build time. If the file is a build input consumed by a strict parser, strip as a build step and keep the commented original as the human-authored source. If a JSONC-aware tool reads it, leave the comments: they document the file for the next editor.
  3. Strip with something string-aware, never a regex. Run the JSON Fix Tool, which attempts a strict parse first and, only on failure, runs a repair pass using the jsonrepair library before re-verifying with a strict parse — or call a JSONC parser directly.
  4. Expect trailing commas to be a separate problem. Removing comments is not sufficient for a document that also has them. The two rewrites are distinct.
  5. Validate the output. Round-trip it through a strict parser before shipping. When the input contains forward slashes, backslashes, or escaped double quotes inside strings, that check is what catches a bad strip.
  6. Format last. The JSON Formatter normalizes indentation afterwards; its indent selector offers 2, 3, 4, or 8 spaces only.

When escaping itself is the problem, the JSON Escape and Unescape Tool handles raw text, following the rules in the guide to JSON escape sequences.

Common mistakes

Treating a clean editor check as valid JSON. The editor's dialect and the consumer's dialect are often not the same.

Stripping comments with a regex. The most damaging shortcut here: it converts a visible parse error into an invisible data error.

Confusing JSON5 with JSONC. A JSON5 document may use unquoted keys and single quotes that a JSONC-aware reader rejects outright. The wider grammar is not a safe fallback.

Leaving blank lines where comments were. Harmless to parsers, but it erases the documentation the comment provided. Strip from a copy.

Assuming repair can recover anything. It is heuristic. A file truncated mid-string may be unrecoverable. The JSON Fix Tool re-verifies with a strict parse and reports failure rather than returning something plausible.

FAQ

Why does JSON not support comments?

Because comments are absent from the grammar. The specification defines six value types and a parser for a JSON text; no production exists that a comment could satisfy. Excluding them guarantees every conforming parser reads a document identically, which is what makes JSON safe as a wire and cache format.

Are comments not allowed in JSON, or merely discouraged?

Not allowed. There is no permissive mode and no standard parser flag that enables them. A parser tolerating comments is a JSONC parser, and no longer a JSON parser.

What file extension should I use for JSON with comments?

Keep .json when the consuming tool expects it — tsconfig.json is the canonical example, and renaming it breaks the tool. For a new data file where you control every reader, .jsonc communicates intent. For a configuration file with a real parser, use that format's own config format (JSON5, TOML, YAML) rather than inventing a convention.

What is the difference between JSON and JSON5?

JSON5 is an independent specification accepting everything JSON accepts plus comments, unquoted keys, single-quoted strings, trailing commas, hex and leading-dot numbers, explicit + signs, Infinity and NaN, and backslash-continued multi-line strings. The two are not interchangeable: JSON5 accepts documents strict tooling must reject, which is why a JSON5 file cannot be handed to JSON.parse.

How do I read a JSON file with comments in Python?

The built-in json module is strict and raises JSONDecodeError on any comment. Use a JSONC or JSON5 parser package, or pre-process the text with a string-aware stripper before calling json.loads. Do not reach for eval, and do not use a regex.

The bottom line

"JSON does not allow comments" is a diagnostic, not a dead end. When a parser rejects your file, it is telling you which dialect you are actually in. Strict JSON is the wire format. JSONC is a Microsoft convention for editor-facing configuration, loose enough that "valid JSONC" does not guarantee your runtime can load the file. JSON5 is a separate, wider specification. And the one thing never to do is delete comments with a regex, because // inside a string is data, not a comment.

Identify the dialect, strip with something that understands string literals, and verify with a strict parse.


🚀 Professional JSON Fixing

The JSON Fix Tool helps you:

  • Correct syntax errors automatically
  • Validate and repair JSON structure instantly
  • Work securely in your browser, with no server uploads
  • Copy or export fixed JSON safely

Fast • Secure • Free