Preserving INI Comments During JSON Conversion

Learn how INI comments (lines starting with ; or #) can be preserved as special keys in JSON and restored when converting back to INI format.

Comments & Edge Cases

Detailed Explanation

Comment Preservation Strategy

INI files frequently contain comments that provide context for configuration values. JSON does not natively support comments, so the converter offers a "Preserve Comments" option that stores them as special keys.

Example INI

; Database configuration
; Updated: 2024-01-15
[database]
; Primary connection
host=db.example.com
port=5432
# Connection pool settings
max_connections=50
idle_timeout=300

JSON with Comments Preserved

{
  "__comment_0": "Database configuration",
  "__comment_1": "Updated: 2024-01-15",
  "database": {
    "__comment_2": "Primary connection",
    "host": "db.example.com",
    "port": 5432,
    "__comment_3": "Connection pool settings",
    "max_connections": 50,
    "idle_timeout": 300
  }
}

JSON without Comments (Default)

{
  "database": {
    "host": "db.example.com",
    "port": 5432,
    "max_connections": 50,
    "idle_timeout": 300
  }
}

How Comment Preservation Works

  1. Each comment line is stored with a sequentially numbered key: __comment_0, __comment_1, etc.
  2. The ; or # prefix is stripped; only the comment text is stored
  3. Comments are associated with their current scope --- global comments go in the root object, section comments go in the section object
  4. When converting back to INI, __comment_* keys are emitted as ; comment text lines

Round-Trip Fidelity

While the exact position of comments relative to keys may shift slightly, the content and scope (global vs. section) are preserved. This enables workflows where you convert INI to JSON for automated processing, then convert back to INI without losing documentation.

Limitations

  • Comment ordering within a section is maintained but their exact line positions are not tracked
  • Multi-line comments are not supported (each line is a separate comment)
  • The __comment_* prefix is reserved; avoid using keys with this prefix in your actual configuration

Use Case

Automating configuration management where INI files need to be parsed into JSON for programmatic modification (adding or changing values) and then written back to INI format while retaining the original documentation comments.

Try It — INI \u2194 JSON Converter

Open full tool