Are Comments Allowed in JSON?

In standard JSON, comments are not allowed. JSON was designed to be a lightweight and simple data interchange format, and comments were intentionally excluded to avoid adding complexity.

According to the official JSON specification (RFC 8259), any text outside the defined JSON syntax is invalid.


What Happens if You Add Comments to JSON?

Adding comments to JSON files will cause most JSON parsers to throw an error. For example:

</>
Copy
// This is a comment
{
  "name": "Alice",
  "age": 25
}

Alternatives to JSON Comments

If you need to add context or explanations to your JSON data, consider the following alternatives:

1. Use a Separate Documentation File

Create a separate file (e.g., a README or documentation file) to describe the structure and purpose of your JSON file.

2. Add Metadata in the JSON Itself

Include descriptive keys in the JSON data to serve as documentation.

</>
Copy
{
  "_comment": "This JSON file contains user information.",
  "name": "Alice",
  "age": 25
}

While this is not standard practice, many developers use the convention of starting keys with an underscore (e.g., _comment) to indicate that they are not actual data fields.

3. Use JSON5 or Other Extensions

If comments are essential, consider using JSON5, a JSON-like format that allows comments and other relaxed syntax features.

</>
Copy
// This is a valid JSON5 file
{
  "name": "Alice", // User's name
  "age": 25       // User's age
}

Note that JSON5 is not compatible with standard JSON parsers, so use it only in environments where it is supported.


Tips for Working Without Comments in JSON

  • Keep JSON files concise and straightforward to minimize the need for comments.
  • Use clear and descriptive keys to make the JSON self-explanatory.
  • Document your JSON files externally or inline in your codebase where the JSON is being used.