TOML Multiline Strings and JSON Escaping
Master TOML's multiline string options: basic multiline strings and literal multiline strings. Learn how they convert to JSON with proper escape sequences.
Detailed Explanation
TOML provides two multiline string types that are far more readable than JSON's single-line strings with escape sequences. Understanding these is essential for configuration files containing long text, templates, or embedded code.
Basic multiline string (triple double quotes):
description = """
This is a multiline string.
It can span multiple lines.
Special characters like \n are processed."""
Converts to JSON:
{
"description": "This is a multiline string.\nIt can span multiple lines.\nSpecial characters like \n are processed."
}
The leading newline after """ is trimmed. Subsequent line breaks become \n in JSON.
Literal multiline string (triple single quotes):
regex = '''
\d{3}-\d{2}-\d{4}
'''
winpath = '''
C:\Users\admin\Documents
'''
Converts to JSON:
{
"regex": "\\d{3}-\\d{2}-\\d{4}\n",
"winpath": "C:\\Users\\admin\\Documents\n"
}
In literal strings, backslashes are not escape characters. They are preserved as-is. This is ideal for regex patterns and Windows file paths.
Line ending backslash (line continuation):
long_text = """\
The quick brown \
fox jumps over \
the lazy dog."""
A backslash at the end of a line trims the newline and leading whitespace on the next line, producing: "The quick brown fox jumps over the lazy dog."
Comparison of TOML string types:
| Type | Syntax | Escapes | Multiline |
|---|---|---|---|
| Basic | "..." |
Yes | No |
| Literal | '...' |
No | No |
| Basic multiline | """...""" |
Yes | Yes |
| Literal multiline | '''...''' |
No | Yes |
Converting JSON multiline strings to TOML:
When a JSON string contains \n characters, a good converter uses TOML's multiline syntax for readability. Strings with backslashes (paths, regex) benefit from literal strings to avoid double-escaping.
Use Case
Embedding SQL queries, shell scripts, or regex patterns in a TOML configuration file where readability matters, and converting them to JSON for consumption by an application that parses JSON configs.