Comments are not allowed in JSON

Standard JSON has no comments of any kind. A // line comment, a /* */ block comment or a # comment is read as an unexpected character, and the error is reported wherever the comment starts: at a key position, after a value, or at position 0. Files such as tsconfig.json and VS Code settings are JSONC, a dialect that allows comments, which is why the same text works in one tool and fails in another.

Seen as:

  • SyntaxError: Expected property name or '}' in JSON at position 4 (line 2 column 3)
  • SyntaxError: Expected ',' or '}' after property value in JSON at position 58 (line 3 column 17)
  • SyntaxError: Unexpected token / in JSON at position 4
  • json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 2 column 3 (char 4)
  • Comments are not permitted in JSON.

Input

Settings

History

Load from URL

Common causes

1. Line comments copied from JavaScript

Configuration examples in documentation are often annotated with //. Remove the comments, or move the notes into the documentation itself.

Before
{
  // API settings
  "baseUrl": "https://api.example.com"
}
After
{
  "baseUrl": "https://api.example.com"
}

2. A block comment after a value

A trailing /* seconds */ makes the parser look for a comma or closing brace and find / instead. If the unit matters, put it in the key name.

Before
{"timeout": 30 /* seconds */}
After
{"timeoutSeconds": 30}

3. A JSONC file read by a strict parser

tsconfig.json, .vscode/settings.json, devcontainer.json and .eslintrc.json are JSONC. Read them with a JSONC-aware parser rather than JSON.parse, or strip the comments first.

Before
const tsconfig = JSON.parse(fs.readFileSync('tsconfig.json', 'utf8'));
After
import { parse } from 'jsonc-parser';
const tsconfig = parse(fs.readFileSync('tsconfig.json', 'utf8'));

4. Hash comments from YAML or shell habits

# comments are not valid in JSON either. If you want comments in a data file, YAML or TOML supports them natively; otherwise store a note as an ordinary field.

Before
{
  # retry policy
  "retries": 3
}
After
{
  "_comment": "retry policy",
  "retries": 3
}

Frequently asked questions

Why were comments left out of JSON?

Douglas Crockford removed them on purpose, because people were using comments to hold parser directives, which would have broken interoperability. He suggested stripping comments with a minifier before parsing if you want them in source files.

What is the difference between JSONC and JSON5?

JSONC is JSON plus // and /* */ comments (and, in most tools, trailing commas). JSON5 goes further, adding single quotes, unquoted keys, hex numbers and more. Neither is accepted by JSON.parse. See the JSON with comments guide.

Can PasteKit strip comments for me?

Yes. Fix it removes // and /* */ comments along with other non-JSON syntax, or you can format the text as JSON5 / JSONC and convert it to strict JSON.

Related