JSON does not officially support comments, which can make documenting configuration files and complex data structures difficult. Developers commonly use the following workarounds:
- Dedicated Keys: Add fields such as _comment to store explanatory text within JSON objects.
- Alternative Formats: Use JSON5 or YAML, which support comments.
- External Documentation: Document the JSON structure and fields in a separate README or schema file.
Using an External Tool or Preprocessor
A preprocessor can remove comments from a JSON-like file before parsing it. This allows developers to write comments using // or other supported syntax, depending on the tool.
// JSON-like input with comments
{
// User's name
"name": "John Doe",
// User's age
"age": 30,
// User's email
"email": "john.doe@example.com"
}
Note: This is not valid standard JSON. A compatible preprocessor must remove the comments before the content is passed to JSON.parse().
Including Comments as Data
Another approach is to add dedicated properties, such as _comment, to store explanatory text. These properties are valid JSON data but become part of the parsed object.
{
"_comment": "This JSON file contains user data",
"name": "John Doe",
"age": 30,
"email": "john.doe@example.com",
"address": {
"_comment": "Address details",
"street": "123 Main St",
"city": "Anytown"
}
}
Note: JSON parsers treat _comment as a regular property, not as a comment. Applications consuming this data must account for these additional fields.