최종 업데이트: 2026년 4월
TOML 형식화란?
TOML(Tom's Obvious Minimal Language)은 Tom Preston-Werner가 2013년에 만든 설정 파일 형식입니다. 해시 테이블에 직접 매핑되며 모든 값에 명시적 타입을 사용합니다. TOML 포매터는 비정형이거나 일관성 없이 작성된 TOML을 받아 균일한 간격, 올바른 들여쓰기, 표준 키 정렬로 재직렬화합니다. 결과물은 프로젝트 전체에서 동일한 규칙을 따르는 파일로, diff에서 설정 변경 사항을 검토하기 훨씬 쉬워집니다.
2021년 1월에 최종 확정된 TOML v1.0.0 사양은 문법을 충분히 엄격하게 정의하여 규격에 맞는 파서라면 동일한 입력에서 동일한 데이터 구조를 생성합니다. 형식화는 TOML 파일의 의미 내용을 변경하지 않습니다. 공백, 키 그룹화, 인용 스타일만 조정합니다. 즉, 애플리케이션 동작이 깨질 걱정 없이 TOML 파일을 자유롭게 형식화할 수 있습니다.
JSON과 달리 TOML은 주석, 네이티브 날짜-시간 타입, 여러 가지 문자열 형식(기본, 리터럴, 여러 줄)을 지원합니다. 좋은 포매터는 주석을 보존하고 인라인 테이블과 표준 테이블 헤더의 차이를 존중합니다. 또한 테이블 배열을 올바르게 처리하여 섹션 그룹화를 유지함으로써 사람과 파서 모두 읽기 쉬운 파일을 유지합니다.
title="My App" version="1.0.0" debug=false [database] host="localhost" port=5432 name="mydb" [database.pool] max_connections=25 timeout=30 [[servers]] name="web" host="web.example.com" [[servers]] name="api" host="api.example.com"
title = "My App" version = "1.0.0" debug = false [database] host = "localhost" port = 5432 name = "mydb" [database.pool] max_connections = 25 timeout = 30 [[servers]] name = "web" host = "web.example.com" [[servers]] name = "api" host = "api.example.com"
TOML 포매터를 사용하는 이유
설정 파일은 팀원들이 시간이 지남에 따라 편집하면서 스타일이 어긋나게 됩니다. 탭과 스페이스가 섞이고, 일부 키에 불필요한 따옴표가 붙고, 테이블 섹션의 시각적 그룹화가 흐트러집니다. TOML 포매터는 이 모든 것을 한 번에 정규화합니다.
TOML 포매터 활용 사례
TOML 문법 참조
TOML에는 소수의 구문 요소가 있습니다. 아래 표는 TOML v1.0.0 사양에 정의된 모든 구조 요소를 나열합니다. 포매터는 이 모든 요소에 일관된 간격과 그룹화를 적용합니다.
| 문법 | 이름 | 비고 |
|---|---|---|
| key = "value" | Basic key-value pair | Keys are bare or quoted; values are typed |
| [table] | Standard table | Creates a named section (hash table) |
| [a.b.c] | Dotted table | Shorthand for nested tables |
| [[array]] | Array of tables | Each [[name]] block appends to an array |
| key = """...\n""" | Multi-line basic string | Allows newlines, escapes processed |
| key = '''...\n''' | Multi-line literal string | Allows newlines, no escape processing |
| # comment | Comment | Extends to end of line; not in JSON output |
| {inline = true} | Inline table | Single-line table, no newlines allowed |
TOML vs JSON vs YAML
TOML, JSON, YAML은 겹치는 문제를 해결하지만 서로 다른 절충안을 선택했습니다.
| 기능 | TOML | JSON | YAML |
|---|---|---|---|
| 주석 | # 줄 주석 | 지원 안 함 | # 줄 주석 |
| 타입 지정 값 | String, int, float, bool, datetime | String, number, bool, null | 추론 방식 (오류 발생 가능) |
| 중첩 구조 | [table] 헤더 | 중괄호 | 들여쓰기 기반 |
| 사양 엄격성 | 엄격 (파싱 결과 하나) | 엄격 (RFC 8259) | 느슨 (복수의 유효한 파싱) |
| 날짜/시간 지원 | 네이티브 타입 4가지 | 없음 (문자열 사용) | 암묵적 (불안정) |
| 후행 쉼표 | 허용 안 함 | 허용 안 함 | 해당 없음 (쉼표 없음) |
코드 예제
아래 예제는 다양한 언어와 도구에서 TOML을 프로그래밍 방식으로 형식화하는 방법을 보여줍니다. 각 예제는 파일을 읽고, 파싱하여 형식화된 버전을 씁니다.
import { parse, stringify } from '@iarna/toml'
import fs from 'fs'
const raw = fs.readFileSync('config.toml', 'utf-8')
const doc = parse(raw)
const formatted = stringify(doc)
// stringify() outputs canonical TOML with consistent spacing
fs.writeFileSync('config.toml', formatted)
// Quick one-liner with npx:
// npx taplo fmt config.tomlimport tomllib # Python 3.11+ (read-only)
import tomli_w # pip install tomli-w (write)
# Parse and re-serialize to format
with open("config.toml", "rb") as f:
data = tomllib.load(f)
formatted = tomli_w.dumps(data)
# tomli_w produces sorted keys, consistent quoting, and
# proper whitespace around = signs
print(formatted)
# CLI alternative: taplo fmt config.tomlpackage main
import (
"fmt"
"os"
"github.com/BurntSushi/toml"
"bytes"
)
func main() {
var data map[string]interface{}
_, err := toml.DecodeFile("config.toml", &data)
if err != nil {
fmt.Fprintln(os.Stderr, err) // parse error with line number
os.Exit(1)
}
var buf bytes.Buffer
enc := toml.NewEncoder(&buf)
enc.Indent = " "
enc.Encode(data) // re-serialized with consistent formatting
fmt.Print(buf.String())
}# Install taplo — the standard TOML toolkit cargo install taplo-cli # or: npm install -g @taplo/cli # Format a single file in place taplo fmt config.toml # Format all .toml files in a project taplo fmt # Check formatting without modifying (CI-friendly) taplo fmt --check # Validate TOML syntax without formatting taplo lint config.toml