JSON Comments: A Complete Guide
JSON (JavaScript Object Notation) is a widely-used data interchange format, but it has one notable limitation: it doesn't natively support comments. This can make it challenging to document configuration files, API responses, or data structures. However, there are several creative workarounds to add comments to JSON. This guide explores the most common methods.
Why JSON Doesn't Support Comments
The JSON specification deliberately excludes comments to keep the format simple and unambiguous. According to Douglas Crockford, JSON's creator, comments were omitted because they could be used to include parsing directives that would break interoperability.
Method 1: Using Special Comment Fields
The most straightforward approach is to add special fields that serve as comments.
Using _comment
Fields
{
"_comment": "User configuration file",
"name": "John Doe",
"_comment_name": "This is the user's display name",
"age": 30,
"preferences": {
"_comment": "User preferences section",
"theme": "dark",
"_comment_theme": "Available themes: light, dark, auto",
"notifications": true
}
}
Using //
Fields
{
"//": "Configuration for the application",
"database": {
"//": "Database connection settings",
"host": "localhost",
"port": 5432,
"//port": "Default PostgreSQL port"
}
}
Using Descriptive Field Names
{
"description": "User profile data structure",
"version": "1.2.0",
"user": {
"id": 12345,
"name": "John Doe",
"email_note": "Primary contact email",
"email": "[email protected]"
}
}
Pros:
- Compatible with all JSON parsers
- Easy to implement
- No special tools required
Cons:
- Increases file size
- Comment fields become part of the data
- Can clutter the actual data structure
- Need to filter out comment fields when processing
Method 2: JSON5 (Recommended)
JSON5 is an extension of JSON that supports comments, among other features. It's backward compatible with JSON while adding useful syntax improvements.
JSON5 Comment Syntax
{
// Single-line comment
"name": "John Doe",
/* Multi-line comment
can span multiple lines */
"age": 30,
// Unquoted keys are allowed
theme: 'dark',
// Trailing commas are allowed
notifications: true,
}
JSON5 Advanced Features
{
// Comments everywhere
name: 'John Doe', // Single quotes allowed
/* Numbers can be:
- Hexadecimal: 0xFF
- Leading/trailing decimal: .5, 2.
- Infinity and NaN
*/
maxValue: Infinity,
hexColor: 0xFF0000,
// Objects and arrays can have trailing commas
hobbies: [
'reading',
'gaming',
'coding', // ← trailing comma
],
}
Using JSON5 in JavaScript
// Install: npm install json5
import JSON5 from 'json5';
const configText = `{
// Application configuration
name: 'MyApp',
version: '1.0.0',
// Database settings
database: {
host: 'localhost',
port: 5432
}
}`;
const config = JSON5.parse(configText);
console.log(config.name); // 'MyApp'
Pros:
- True comment support (single-line and multi-line)
- Backward compatible with JSON
- Additional useful features (unquoted keys, trailing commas)
- Growing ecosystem support
Cons:
- Requires special parser
- Not supported by all tools and systems
- Slight learning curve for additional syntax
Method 3: JSONC (JSON with Comments)
JSONC is JSON with C-style comments, primarily used by Microsoft tools like VS Code.
{
// This is a single-line comment
"name": "John Doe",
/* This is a
multi-line comment */
"settings": {
"theme": "dark", // Inline comment
"fontSize": 14
}
}
Pros:
- Simpler than JSON5 (only adds comments)
- Supported by VS Code and related tools
- Familiar C-style comment syntax
Cons:
- Limited tool support
- Not a formal standard
- Requires special parser
Method 4: External Documentation
Keep JSON clean and maintain separate documentation files.
JSON File (config.json)
{
"database": {
"host": "localhost",
"port": 5432,
"ssl": true
},
"logging": {
"level": "info",
"file": "/var/log/app.log"
}
}
Documentation File (config.md)
# Configuration Guide
## Database Section
- `host`: Database server hostname
- `port`: Database port (default: 5432)
- `ssl`: Enable SSL connection
## Logging Section
- `level`: Log level (debug, info, warn, error)
- `file`: Log file path
Pros:
- Pure JSON remains clean and standard
- Detailed documentation possible
- Can include examples and usage instructions
Cons:
- Separate files to maintain
- Comments are not inline with data
- Risk of documentation becoming outdated
Method 5: Schema-Based Documentation
Use JSON Schema to document your data structure.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "User Configuration",
"description": "Configuration file for user preferences",
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "User's display name"
},
"theme": {
"type": "string",
"enum": ["light", "dark", "auto"],
"description": "UI theme preference"
}
}
}
Pros:
- Provides validation and documentation
- Tool support for auto-completion
- Industry standard
Cons:
- Complex for simple use cases
- Schema files can be verbose
- Requires schema-aware tools
Best Practices and Recommendations
1. Choose Based on Use Case
- Configuration files: Use JSON5 for maximum flexibility
- API responses: Stick to standard JSON (no comments needed)
- Documentation: Use JSON Schema for complex data structures
- Quick prototyping: Use comment fields method
2. Tool Compatibility
Before choosing a method, consider:
- What tools will parse your JSON?
- Do your build systems support the chosen format?
- Will other team members understand the format?
3. Migration Strategy
If migrating from JSON to JSON5:
// 1. Start with valid JSON
const originalJson = '{"name": "value"}';
// 2. Gradually add JSON5 features
const json5Version = `{
// Added comments
name: "value" // Removed quotes from key
}`;
// 3. Update parsers in your codebase
// Replace JSON.parse() with JSON5.parse()
4. IDE and Editor Support
Popular editors with JSON5/JSONC support:
- VS Code (built-in JSONC support)
- WebStorm/IntelliJ IDEA
- Sublime Text (with plugins)
- Vim/Neovim (with plugins)
Conclusion
While JSON doesn't natively support comments, you have several options:
- For maximum compatibility: Use comment fields (
_comment
,//
) - For modern projects: Use JSON5 (recommended)
- For VS Code projects: Use JSONC
- For complex schemas: Use JSON Schema documentation
- For simple cases: Use external documentation
JSON5 strikes the best balance between functionality and compatibility, making it the recommended choice for most new projects that need commented JSON.
Tools and Libraries
JSON5 Parsers
- JavaScript:
json5
npm package - Python:
pyjson5
package - Java:
json5-java
library - C#:
Json5.NET
package - Go:
json5
package