Can You Use Comments in JSON Files?


Here’s the Truth

Quick Answer

No, standard JSON does not support comments.

Trying to insert // or /* */ style comments will cause a parsing error in strict JSON parsers.

So… Why Not?

JSON (JavaScript Object Notation) was designed to be a lightweight data format — easy to read and write for humans, and easy to parse for machines. The specification intentionally excludes comments to ensure that JSON is purely data-driven and not a place for annotations or notes.


What Happens If You Try to Add Comments?

Example:

{
  // this is a comment
  "name": "Alice",
  "age": 30
}

Or:

{
  "name": "Alice", /* inline comment */
  "age": 30
}

Both will throw errors in parsers like:

Unexpected token '/' at position 5

So, the takeaway? Don’t do it in production JSON files.


Workarounds If You Really Want Comments

If you absolutely need to include human-readable notes in your JSON file, here are some acceptable (non-breaking) workarounds:

1. Add a Fake Property

{
  "_comment": "This file contains basic user info",
  "name": "Alice",
  "age": 30
}

✅ Works in all parsers because it’s just another string field.

🚫 But keep in mind: it will be treated like data — not ignored.


2. Use JSONC (JSON with Comments)

Tools like VS Code, TypeScript config files, and some linters support a relaxed JSON format called JSONC, which allows comments:

// This is okay in JSONC
{
  "name": "Alice",
  "age": 30
}

Just remember — JSONC isn’t standard. If your tool expects raw JSON, it’ll break.


3. Pre-Processing Strategy

Write your JSON with comments, then use a script to strip them before parsing.

Example in Node.js:

const fs = require('fs');
const stripJsonComments = require('strip-json-comments');

const jsonWithComments = fs.readFileSync('config.json', 'utf8');
const cleanJson = JSON.parse(stripJsonComments(jsonWithComments));

This lets you keep comments in dev without breaking the parser in production.


Why the Controversy?

Many developers argue comments are essential for config files and collaboration. Even JSON’s creator, Douglas Crockford, has acknowledged this — but stood by the spec for simplicity and consistency.

If you need comments, consider using YAML instead.


Final Thoughts

  • Standard JSON = No comments allowed
  • JSONC or _comment key = Workarounds, not standards
  • Need more flexibility? → Switch to YAML or preprocess JSON
Previous Article

Is Java Pass-by-Reference or Pass-by-Value? A Clear Explanation

Next Article

What Does the Yield Keyword Do in Python? A Beginner’s Guide

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨