Programming

Can Comments Be Used in JSON Files? Workarounds

JSON files don't support comments natively, causing parser errors with // or /* */. Discover workarounds like JSON5, _comment keys, preprocessing, JSON Schema $comment, and alternatives for adding notes to JSON effectively.

1 answer 6 views

Can comments be used in JSON files? If so, how?

JSON files do not support comments natively — putting // or /* */ into a .json will usually make standard parsers throw a syntax error. If you need annotations, use a JSON superset that allows comments (JSON5/Hjson), embed notes as data fields (e.g., “_comment”), strip comments before parsing with a preprocessor, or put notes in external docs; for schema files you can use the JSON Schema $comment keyword.


Contents


Can comments be used in JSON files?

Short answer: no, not in standard JSON. The JSON specification intentionally omits comment syntax; if you insert // or /* */ into a .json file, most standard parsers will raise a syntax error and refuse to parse the file (see this practical guide on why comments break JSON and what happens when parsers encounter them) — for an accessible explanation see the freeCodeCamp guide on comments in JSON.

There is one special-case for schema documents: JSON Schema defines a $comment keyword that you may include inside a schema file; it’s a string value meant for humans and tooling, not for altering validation rules (see the JSON Schema docs on $comment).


Why JSON doesn’t support comments

Why leave comments out? Two short reasons: simplicity and interoperability. JSON’s creator and the community removed comment syntax to avoid two common problems: people embedding processor directives or metadata in comments (which can break portability), and divergent parsers that treat comments differently. The result is a very small, strict format that’s simple to parse reliably across languages and platforms — but that strictness means you lose the convenience of inline human notes.

If you want the historical and practical perspective on that trade-off, there are good write-ups and community discussions that explain the rationale and show typical workarounds (see discussions on Stack Overflow and the Medium write-up that cites Douglas Crockford’s reasoning).


How to add comments to JSON files (workarounds & alternatives)

There are several practical approaches. Pick one based on who consumes the file (humans vs machines), whether the file is public API output, and how much tooling you can control.

1) Use a superset (JSON5 / Hjson)

If you control both producers and consumers, use a JSON superset that supports comments and extra conveniences. JSON5 and Hjson allow // and /* */ comments and still map cleanly to JSON-like structures. The trade-off: every consumer must use a JSON5/Hjson-aware parser.

Example JSON5:

json5
// config.json5
// Single-line comment
{
 name: "Alice", // trailing comment
 /* multi-line
 comment */
 port: 8080
}

Parse in Node.js:

js
const fs = require('fs');
const JSON5 = require('json5'); // npm install json5
const config = JSON5.parse(fs.readFileSync('config.json5', 'utf8'));

See a practical overview and examples of JSON5 and other supersets in coding guides that compare approaches.

2) Embed comments as data keys (the “_comment” pattern)

Put notes into the JSON as ordinary key/value pairs that your application ignores. This keeps the file valid JSON for standard parsers.

Example:

json
{
 "_comment": "This config is for staging only — do not use in production.",
 "host": "staging.example.com",
 "port": 8080
}

Then, in code, drop or ignore those keys:

js
const cfg = JSON.parse(fs.readFileSync('config.json', 'utf8'));
const { _comment, ...config } = cfg; // remove comment before use

Pros: works with any JSON parser. Cons: comments become part of the data payload (bigger files, possible accidental exposure), and every consumer must agree to ignore those keys.

3) Strip comments before parsing (preprocessing)

If developers want to keep using // or /* */ in source files but must deliver strict JSON at runtime, add a small preprocessing step that removes comments before JSON.parse. Libraries exist for this (and many projects implement this as a build step). This preserves readable files while passing strict JSON to downstream systems.

Example workflow:

  • Write a file with comments.
  • At runtime or during CI, run a strip-step to produce pure JSON.
  • Parse the cleaned JSON.

Simple Node.js pattern (using a comment-stripper library or trusted preprocessor) keeps things safe. Beware: hand-rolled regex removers can fail on tricky inputs (strings containing //); prefer well-tested libraries.

4) Use an alternate config format or external docs (YAML, TOML, README)

If human-editability is your priority, use a format designed for it. YAML and TOML support comments natively and are widely supported as config file formats. Another lightweight option is to keep JSON minimal and put explanatory text in README.md or dedicated documentation files. This avoids polluting data with notes.

Sentry and other tooling guides often recommend switching to YAML/TOML or keeping comments outside the JSON when configuration readability is essential.

5) Use $comment in JSON Schema (schemas only)

If you’re documenting a schema (not application data), use the JSON Schema $comment keyword. It’s allowed in schema documents and intended for human-facing notes or tooling; schema validators must treat it as non-functional metadata. Example:

json
{
 "$comment": "Schema for API payload v1",
 "type": "object",
 "properties": {
 "country": {
 "$comment": "TODO: consider replacing with an enum",
 "type": "string"
 }
 }
}

See the JSON Schema docs for details and examples.


Practical examples and pitfalls to avoid

  • Example of invalid JSON (comments cause parse error):
json
{
 // this will break
 "name": "Alice"
}

Try running JSON.parse on that and you’ll see a syntax error. Guides and tutorials repeatedly show this failing case to illustrate why comments aren’t allowed.

  • Example: using “_comment” safely

  • Pros: compatible with any JSON parser.

  • Cons: the comment becomes data; if you send that JSON to an API, you may leak those notes. Also, downstream consumers must ignore keys by convention.

  • Example: using a preprocessor

  • Pros: keeps source readable, produces strict JSON for consumers.

  • Cons: adds a build/runtime step; must be robust (don’t accidentally strip comment-like text inside strings).

Common pitfalls:

  • Committing comment-bearing JSON to services that expect strict JSON (third-party APIs, servers) — they’ll reject it.
  • Assuming every language ecosystem supports JSON5/Hjson — they may not, and that breaks portability.
  • Using naive regex to strip comments — edge cases exist (e.g., URLs, strings containing “/*”) that can corrupt data.

When in doubt, keep machine-exposed JSON pure. Use human-friendly formats where human edits are required.


Choosing the right approach for your project

  • Public APIs and data interchange: never include comments. Produce strict, minimal JSON.
  • Internal tools/configs where you control both sides: JSON5 or Hjson can be a productivity win.
  • Cross-language or library-agnostic configs: prefer YAML or TOML, or keep annotations outside the JSON.
  • Schema documentation: use $comment inside JSON Schema files.
  • Quick notes for maintainers: a README or CHANGELOG is low-risk and tool-agnostic.

Ask yourself: who consumes the file, and can they accept a non-standard parser? If the answer is no, don’t add inline comments — pick one of the safe workarounds instead.


Sources


Conclusion

Standard JSON does not support comments; putting // or /* */ into a .json will usually break parsers. If you need in-file notes, use a controlled JSON superset (JSON5/Hjson), embed comment keys that consumers ignore, or strip comments during a preprocessing step — and use $comment only inside JSON Schema files. For cross-system or public data, prefer keeping JSON pure and put documentation in external files.

Authors
Verified by moderation
Moderation
Can Comments Be Used in JSON Files? Workarounds