TOML Arrays and JSON Arrays
Learn how TOML arrays map to JSON arrays. Covers basic arrays, multiline arrays, and the important TOML rule that array elements must share the same type.
Detailed Explanation
TOML arrays map directly to JSON arrays, but with one significant restriction: TOML requires all elements in an array to be of the same type. This is a deliberate design choice that makes TOML configurations more predictable.
Basic TOML arrays:
ports = [8001, 8002, 8003]
hosts = ["alpha", "beta", "gamma"]
enabled = [true, false, true]
Converts to JSON:
{
"ports": [8001, 8002, 8003],
"hosts": ["alpha", "beta", "gamma"],
"enabled": [true, false, true]
}
Multiline arrays (for readability):
contributors = [
"Alice",
"Bob",
"Charlie",
]
TOML allows trailing commas in multiline arrays, which JSON does not. The converter strips trailing commas when producing JSON.
Nested arrays:
data = [[1, 2], [3, 4, 5]]
Converts to: {"data": [[1, 2], [3, 4, 5]]}
Nested arrays are valid as long as each sub-array is homogeneous within itself.
The type restriction:
In TOML, this is invalid:
# ERROR: mixed types in array
mixed = [1, "two", true]
JSON happily accepts mixed-type arrays, but TOML does not. When converting JSON to TOML, mixed-type arrays must be restructured -- for example, by converting all elements to strings or splitting into separate typed arrays.
Arrays of inline tables:
points = [{x = 1, y = 2}, {x = 3, y = 4}]
Converts to:
{
"points": [{"x": 1, "y": 2}, {"x": 3, "y": 4}]
}
This is valid because each element is an inline table (object) with the same structure.
Use Case
Defining lists of allowed values, port numbers, or hostnames in a TOML configuration file, and understanding how to ensure type consistency when converting from JSON arrays that may contain mixed types.