JSON is designed to store and exchange structured data, so it does not support comments in the same way as programming languages such as JavaScript, Python, or Java. That limitation often surprises developers who want to leave notes beside configuration values, explain an API field, or temporarily disable part of a data file.
The standard answer is simple: valid JSON cannot contain comments. Adding // or /* */ syntax makes the document invalid for strict JSON parsers. Still, there are several practical ways to document JSON safely, depending on where the file is used. You can add a reserved field such as “_comment”, use a JSON-compatible configuration format, maintain documentation outside the file, or rely on a preprocessing step.
This guide explains how to comment in JSON without breaking parsing, shows working examples, compares available alternatives, and explains when each approach makes sense. You will also learn how different tools treat comments, why some editors appear to allow them, and how to avoid common problems in configuration files and API payloads.
Why Standard JSON Does Not Support Comments
JSON stands for JavaScript Object Notation, but it is a data format rather than a general-purpose programming language. Its specification defines values such as objects, arrays, strings, numbers, true, false, and null. Comment syntax is not part of that standard.
In JavaScript, comments begin with // or are wrapped between /* and */. Those characters are not recognized as comments by a strict JSON parser. Instead, the parser treats them as unexpected content and returns a syntax error.
For example, this is not valid JSON:
{
// Stores the application name
“name”: “Example App”
}
The same problem occurs with block comments:
{
/*
Stores the application name
*/
“name”: “Example App”
}
A strict parser may report an error near the slash, a missing property name, or an unexpected token. The exact message depends on the programming language and parser, but the underlying issue is the same: comments are not allowed by standard JSON.
The Core Difference Between JSON and JavaScript Objects
JavaScript source code can contain comments because JavaScript has its own grammar. A JavaScript object literal may look similar to JSON, but the two formats are not interchangeable in every situation.
This JavaScript object is valid:
const settings = {
// The server port
port: 3000
};
The equivalent JSON must omit the comment:
{
“port”: 3000
}
JSON also requires double-quoted property names and string values. JavaScript may allow unquoted property names, single-quoted strings, trailing commas, functions, and other features that JSON does not permit.
That distinction matters when a file is loaded by an API, imported by a database, or parsed with a standard JSON library. A file that works in a JavaScript development environment may fail when another system expects strict JSON.
Can You Use Slash Comments in JSON
No. Standard JSON does not allow single-line comments beginning with //.
The following example is invalid:
{
“name”: “Example App”,
// “debug”: true
}
Even though the commented property looks harmless, a strict parser still sees the slash characters. It does not know that the line was intended to be ignored.
Can You Use Block Comments in JSON
No. Standard JSON does not support block comments enclosed by /* and */.
This example is also invalid:
{
“name”: “Example App”,
/* “debug”: true */
}
Some JSON-like tools accept block comments as an extension, but that behavior belongs to the tool rather than the JSON standard. If the file may be consumed by different applications, relying on this extension can create compatibility problems.
Safe Ways to Add Notes to JSON
When comments are needed, the best solution depends on whether the file must remain valid JSON. The following methods are the most practical options.
- Add a dedicated metadata property such as "_comment" or "_description".
- Store explanations in a separate README or documentation file.
- Use a format that supports comments, such as YAML or JSON5, when the receiving system allows it.
- Use a preprocessing step that removes comments before strict parsing.
- Put notes in version-control commits, pull requests, or configuration documentation.
- Use descriptive property names and structure to make the data easier to interpret.
The first two approaches preserve compatibility most reliably. Alternative formats can be more convenient, but only when every tool in the workflow supports them.
Use a Dedicated Comment Property
The simplest way to place a note inside valid JSON is to add a normal property whose name clearly indicates that it contains documentation.
For example:
{
“_comment”: “The timeout is measured in seconds.”,
“timeout”: 30
}
This is valid JSON because “_comment” is an ordinary key with a string value. A parser can read it without errors.
You can use other names, including “_description”, “_notes”, or “$comment”. The name should match the conventions of your project. Some schemas and APIs use “$comment” specifically for annotations, while internal configuration files often use “_comment”.
A comment property can also appear beside a group of
{
“database”: {
“_comment”: “Use the staging database for local testing.”,
“host”: “staging.example.com”,
“port”: 5432
}
}
This keeps the explanation close to the settings it describes.
Important Limitations of Comment Properties
A comment property is still data. It is not ignored automatically by every application. If a program loops through all properties, validates every key, or sends the object to an API, the extra field may be processed or transmitted.
For that reason, comment properties are best suited to internal configuration files, examples, fixtures, and documentation-oriented data. They may not be appropriate in request bodies sent to a strict API that rejects unknown fields.
Before adding a metadata key, check how the consuming application handles unknown properties. A configuration loader may ignore “_comment”, while an API schema may reject it with a validation error.
Use a Separate Documentation File
A separate README, configuration guide, or schema description is often the cleanest approach for production JSON. The JSON remains pure data, while the explanations can be as detailed as necessary.
For example, a project might contain:
config.json
config.example.json
CONFIGURATION.md
The JSON file contains only values:
{
“host”: “localhost”,
“port”: 3000,
“timeout”: 30
}
The documentation file explains what each setting means, acceptable ranges, security considerations, and environment-specific recommendations.
This method works especially well when several fields need lengthy explanations. It also avoids sending documentation fields to an API or forcing application code to ignore metadata keys.
A useful internal link can support readers who need more detail about the data structure: [JSON configuration file best practices]. Documentation should explain required fields, optional fields, data types, defaults, and examples of valid values.
Use an Example File for Configuration Documentation
Many projects provide a safe template such as config.example.json rather than adding comments directly to the live configuration file.
For example:
{
“apiUrl”: “https://api.example.com”,
“apiKey”: “replace-with-your-key”,
“requestTimeout”: 30
}
A related README can explain each value. The real config.json can then remain untracked, private, and strictly valid.
This pattern is useful for credentials, deployment settings, database connections, and other values that differ between developers or environments. It also reduces the chance of committing secrets to source control.
Use JSON5 When Comments Are Required
JSON5 is an extended format based on JSON that supports comments, trailing commas, unquoted property names in some situations, and other conveniences. A JSON5 file may contain:
{
// Time limit for outgoing requests
“timeout”: 30,
}
This is easier for humans to maintain, but it is not standard JSON. The file must be parsed with a JSON5-compatible library or converted into regular JSON before another system reads it.
JSON5 is a reasonable choice for developer-maintained configuration when the application explicitly supports it. It is not suitable when a third-party service requires a strict .json file.
Check the file extension and parser expectations before switching formats. Renaming a JSON5 file to .json does not make it valid JSON, and a standard parser will still reject its comments.
Use YAML for Human-Maintained Configuration
YAML supports comments and is often chosen for configuration files that people edit regularly.
A YAML equivalent might look like this:
# The request timeout is measured in seconds.
timeout: 30
host: localhost
YAML can be easier to annotate than JSON, but it has different syntax, data-type rules, and parsing behavior. Indentation is significant, and some YAML values may be interpreted differently than expected.
Use YAML only when the application, deployment system, or build process supports it. Converting between YAML and JSON can also introduce differences, especially with dates, booleans, null values, and multiline strings.
When a strict JSON output is required, YAML may serve as a source format that is converted during a build step. The generated JSON should then be validated before deployment.
Use a Preprocessor for Commented Source Files
Some projects maintain a source file with comments and generate clean JSON before it is consumed. A preprocessor can remove comments, substitute environment values, or combine multiple configuration fragments.
The workflow usually looks like this:
1. Write a human-maintained source file using a supported extended syntax.
2. Run a build or preparation command.
3. Remove comments and unsupported syntax.
4. Generate standard JSON.
5. Validate the generated file.
6. Send or deploy the valid output.
This approach is powerful, but it adds build complexity. The source file and generated file must be clearly identified, and developers need to know which one should be edited.
Do not remove comments with a simple text replacement unless the tool understands strings correctly. A slash sequence inside a quoted URL or regular expression can be mistaken for comment syntax. Use a parser or purpose-built conversion tool whenever possible.
Commenting JSON in Common Development Environments
Different editors and tools may appear to support comments in JSON. This often happens because they recognize JSON with Comments, commonly abbreviated JSONC, or because a language server offers relaxed parsing for configuration files.
Visual Studio Code, for example, uses JSONC for some files such as settings and launch configurations. These files may allow // and /* */ comments even though ordinary JSON does not.
That behavior is specific to the file type and editor tooling. A file accepted by an editor may still fail when loaded by a standard JSON parser, uploaded to an API, or processed by another application.
Before using comments, identify the actual consumer:
- A code editor may support JSONC.
- A build tool may support JSON5.
- A web API usually expects strict JSON.
- A package manager may define its own relaxed format.
- A programming language library may reject every nonstandard feature.
- A command-line tool may provide a separate flag for relaxed parsing.
The safest practice is to follow the format documented by the receiving system rather than relying on editor behavior.
Valid JSON Examples for Documentation
A short note can be represented as a metadata field:
{
“_comment”: “This value must match the public application URL.”,
“url”: “https://app.example.com”
}
Multiple notes can be stored in an array:
{
“_comments”: [
“Use a secure connection in production.”,
“The retry count must be a nonnegative integer.”
],
“retries”: 3,
“secure”: true
}
A description can be attached to a nested object:
{
“logging”: {
“_description”: “Controls application logging output.”,
“level”: “warning”,
“file”: “app.log”
}
}
These examples remain valid JSON, but the application must tolerate the additional fields. If the object is intended for an external API, keep the notes outside the payload unless the API explicitly documents support for them.
Invalid JSON Examples to Avoid
This example fails because it contains a line comment:
{
“enabled”: true,
// Turn this off during maintenance
“maintenance”: false
}
This example fails because it contains a block comment:
{
“enabled”: true,
/* Temporary setting */
“maintenance”: false
}
This example also fails in strict JSON because it leaves a trailing comma after the final property:
{
“enabled”: true,
}
Comments are not the only source of JSON errors. Single quotes, unquoted keys, trailing commas, and accidental extra text can also cause parsing failures.
Common Problems and Practical Fixes
A file that looks correct in an editor may fail when an application loads it. The most common reason is that the editor is using a relaxed JSON dialect while the application uses a strict parser.
When that happens, remove comments, trailing commas, and other extensions. Then validate the file with the same type of parser used in production. Testing only inside an editor is not enough.
Another common issue is adding “_comment” to an API request. The API may reject the request because its schema allows only known fields. In that case, move the explanation to external documentation or use the API’s official description mechanism.
A third issue occurs when comments become outdated. A note that says “the timeout is five seconds” becomes misleading after the value changes to 30. Keep documentation close to the change process, and update notes whenever the related data changes.
Best Practices for Maintainable JSON
Use descriptive keys before adding explanatory notes. A property named “requestTimeoutSeconds” communicates more than a vague key named “timeout”.
Keep comments short when they must be stored inside the data. A concise note is easier to maintain and less likely to distract from the actual values.
Document reasons, constraints, and risks rather than repeating the value. For example, “Must remain below 60 because the upstream service rejects longer requests” is more useful than “Timeout is 30.”
Validate every file after editing. A formatter or linter can catch invalid syntax before the file reaches an application, build process, or deployment system.
Use version control for historical explanations. Commit messages and pull requests are better places to record why a setting changed, especially when the reasoning is temporary or tied to a specific incident.
Keep secrets out of examples and comments. A note inside a configuration file can still be exposed through source control, logs, backups, or API requests.
Choosing the Right Method
The best method depends on the file’s purpose and the systems that read it.
| Situation | Recommended approach |
|—|—|
| Public API request body | Keep comments outside the JSON |
| Internal configuration file | Use a reserved metadata property if supported |
| Editor-specific settings file | Follow the editor’s JSONC documentation |
| Developer-maintained configuration | Consider JSON5 or YAML |
| Generated deployment file | Document the source file and validate generated JSON |
| Educational example | Use a separate explanation or clearly labeled metadata |
| Shared data exchanged between systems | Use strict JSON without comments |
This decision prevents a common mistake: choosing the most convenient syntax for the writer without checking what the reader accepts.
A short project README may be enough for a small file. A larger system may need a schema, configuration reference, example file, validation rules, and environment-specific documentation. The goal is not merely to place text near a value; it is to preserve reliable communication between people and software.
Testing and Validation Workflow
When modifying a JSON file, use a repeatable validation process.
1. Save the file with valid JSON syntax.
2. Run the project’s formatter or linter.
3. Parse the file with the application’s expected library.
4. Test required fields and data types.
5. Confirm that no documentation fields are sent where they are forbidden.
6. Review the resulting data before deployment.
For a quick command-line check, many systems provide a JSON parser such as jq. A command like this can validate a file:
jq empty config.json
If the file is valid, the command usually produces no output and returns a successful status. If it contains comments or another syntax error, jq reports the location of the problem.
You can also validate JSON with the language used by your application. This is preferable when the application applies additional schema rules beyond basic JSON syntax.
Troubleshooting Parser Errors
When a parser reports an error, inspect the line mentioned in the message and the line immediately before it. A missing comma or an extra comma often causes the parser to complain later than the actual mistake.
If the error points to a slash, check for // or /* comments. If it points to a quotation mark, look for an unescaped quote inside a string. If it reports an unexpected character near the end of an object, check for a trailing comma or unmatched brace.
Copying JSON from documentation can also introduce invisible characters, smart quotes, or code fences. Make sure the file contains only the JSON data and not surrounding Markdown markers such as “`json.
When using an extended format, confirm that the correct parser is being called. A JSON5 file sent to a standard JSON parser will fail even when its syntax is valid according to JSON5 rules.
Do and Do Not Practices
Do use a separate documentation file when the data is exchanged with external systems.
Do choose a documented extension such as JSONC or JSON5 when your toolchain explicitly supports it.
Do validate the final output with a strict parser when compatibility matters.
Do use metadata properties only when the consuming application ignores or accepts them.
Do keep configuration examples free from credentials and private tokens.
Do not assume that an editor’s syntax highlighting proves a file is valid JSON.
Do not add comments directly to API payloads unless the API documentation allows them.
Do not use a text replacement script that can corrupt URLs, strings, or escaped characters.
Do not leave temporary notes in production configuration without an owner or removal plan.
Do not confuse a JavaScript object with a standard JSON document.
Related Documentation and Further Reading
Teams that work with configuration files may also benefit from a clear [JSON schema validation guide]. A schema can describe required properties, allowed types, minimum values, and permitted structures without placing explanatory comments in the data itself.
For larger projects, combine schemas with a configuration reference. The schema protects machine-readable correctness, while the reference explains how people should choose values and why certain constraints exist.
This division keeps responsibilities clear: JSON stores the data, schemas validate the shape, and documentation explains the purpose.
Conclusion
Standard JSON does not support comments, so inserting // or /* */ into a strict JSON file will cause parsing errors. The safest alternatives are to document the file separately, use a reserved metadata property when the application permits it, or choose a supported format such as JSONC, JSON5, or YAML.
The correct choice depends on the system reading the file. Internal configuration may tolerate a “_comment” field, while an external API may reject it. An editor may accept comments through a relaxed dialect even though the same file fails in production.
When deciding how to comment in json, start by identifying the parser, schema, and deployment process. Keep standard JSON clean when compatibility matters, validate files with the real consumer, and place longer explanations in a README, schema, or configuration reference. Good documentation should clarify intent without turning useful data into an unreliable file.
Frequently Asked Questions
Can JSON contain comments?
No. Standard JSON does not include comment syntax. Comments beginning with // or enclosed in /* and */ make the document invalid for strict parsers. Use external documentation, metadata fields, or a supported JSON extension instead.
What is the safest alternative to comments in JSON?
A separate README or configuration reference is usually safest because it keeps the JSON valid and prevents extra fields from reaching an API. For internal files, a documented “_comment” property may also work.
Why does my editor allow comments in a JSON file?
Your editor may be treating the file as JSONC, JSON5, or another relaxed format. Editor support does not guarantee compatibility with standard JSON parsers, APIs, command-line tools, or deployment systems.
Can I use a comment property in an API request?
Only if the API explicitly allows unknown or documentation fields. Many APIs validate request bodies strictly and reject keys such as “_comment”. Keep notes outside the payload unless the API documents a supported annotation field.
Is JSON5 the same as JSON?
No. JSON5 extends JSON with features such as comments, trailing commas, and more flexible syntax. It requires a JSON5-compatible parser or conversion step, while standard JSON can be read by ordinary JSON parsers.