YAML Comments and JSON Conversion

Understand how YAML comments work and why they're lost during JSON conversion. Learn strategies for preserving documentation when converting between formats.

Syntax

Detailed Explanation

Comments are one of the most significant differences between JSON and YAML. YAML fully supports comments using the # character, while JSON has no comment syntax at all. This makes YAML much more suitable for configuration files that need inline documentation.

YAML with comments:

# Database configuration
database:
  host: localhost       # Primary database host
  port: 5432           # Default PostgreSQL port
  name: myapp_prod     # Production database name
  # Connection pool settings
  pool:
    min: 5             # Minimum connections
    max: 20            # Maximum connections
    # Idle timeout in milliseconds
    idle_timeout: 30000

After conversion to JSON, all comments are removed:

{
  "database": {
    "host": "localhost",
    "port": 5432,
    "name": "myapp_prod",
    "pool": {
      "min": 5,
      "max": 20,
      "idle_timeout": 30000
    }
  }
}

This is irreversible. Once converted to JSON, the comments cannot be recovered. Converting that JSON back to YAML produces valid YAML but without any of the original documentation.

Strategies for preserving documentation:

  1. Keep YAML as the source of truth. If comments matter, maintain the YAML file as the canonical version and generate JSON from it when needed.
  2. Use description fields. Add documentation as data values: "_comment": "This explains the setting". Note that this adds extra data to the structure.
  3. External documentation. Maintain a separate README or schema file that documents the configuration.

JSON with comments (JSONC): Some tools support JSONC (JSON with Comments), which allows // and /* */ comments. TypeScript's tsconfig.json and VS Code's settings.json use this format. However, JSONC is not standard JSON and most parsers will reject it.

Comment placement in YAML:

# Full-line comment
key: value  # Inline comment (space before # is required)
# key: old_value  # Commented-out configuration

Comments are invaluable for explaining why a configuration value was chosen, not just what it is.

Use Case

Maintaining a well-documented YAML configuration file for a team project where inline comments explain non-obvious settings, while generating a comment-free JSON version for the application to consume at runtime.

Try It — JSON ↔ YAML Converter

Open full tool