JSON5 vs TOML: In-Depth Comparison

Two commentable config formats with very different ideas about structure.

JSON5 extends JSON with JavaScript-style syntax, so nesting is drawn with braces. TOML starts from key and value lines grouped under table headers, and adds real date and time types. Both formats let you write comments next to settings.

This page compares both against their specifications, runs the same data through real parsers, shows where conversion silently loses information, and says plainly when TOML is the better choice for a project.

The same service config drawn as nested JSON5 braces and as TOML table headers on two screens

TL;DR: Pick TOML when the file is mostly flat sections of settings, needs dates and times, or lives in an ecosystem that already mandates it (Cargo, Python packaging). Pick JSON5 when the data is deeply nested, may contain null, has a top-level array, or is read by JavaScript tools that already speak JSON. Converting between them is not lossless.

Compare icon

JSON5 and TOML at a Glance

The two formats answer different questions. JSON5 asks how to make JSON pleasant to write by hand while keeping its data model. Its specification, version 1.0.0 dated March 2018, builds on JSON and borrows syntax from ECMAScript 5.1. TOML (Tom's Obvious, Minimal Language) states its own objective as being a minimal configuration format that is easy to read and that maps unambiguously to a hash table. Version 1.0.0 was released on January 11, 2021, and version 1.1.0 on December 18, 2025.

PropertyJSON5TOML 1.1.0
Top-level valueAny value: object, array, string, number, boolean or nullAlways a table
Nesting styleBraces and bracketsTable headers, dotted keys, inline tables
Key and value separator:=
Comments// and /* */# to end of line only
Trailing commasYesYes in arrays; in inline tables since 1.1.0
NullYesNo
Date and time typesNoFour distinct types
Integer and float distinctionNone: one number typeSeparate types
Duplicate keysBehavior unpredictable per the specInvalid
IndentationNot significantNot significant
File extension.json5.toml
Media typeNo entry in the IANA application registryapplication/toml, registered with IANA

Neither format gives whitespace indentation any meaning, which separates both of them from YAML. For the wider picture across several formats, see the comparison overview.

Code file icon

The Same Config, Side by Side

Here is one service configuration with a nested section and a list of workers. First in JSON5:

// service.json5 { title: 'Billing service', debug: false, server: { host: '127.0.0.1', port: 8080, timeouts: { read: 5.5, write: 10 }, }, workers: [ { name: 'invoices', concurrency: 4, queues: ['new', 'retry'] }, { name: 'emails', concurrency: 2, queues: ['outbound'] }, ], }

Then in TOML:

# service.toml title = "Billing service" debug = false [server] host = "127.0.0.1" port = 8080 [server.timeouts] read = 5.5 write = 10 [[workers]] name = "invoices" concurrency = 4 queues = ["new", "retry"] [[workers]] name = "emails" concurrency = 2 queues = ["outbound"]

We parsed both with the json5 package (2.2.3) and smol-toml (1.9.1) on Node.js 24 and compared the results; they describe the same data. The JSON round trip below only normalizes object prototypes before the strict comparison.

import { readFileSync } from 'node:fs'; import { isDeepStrictEqual } from 'node:util'; import JSON5 from 'json5'; import { parse } from 'smol-toml'; const a = JSON5.parse(readFileSync('service.json5', 'utf8')); const b = parse(readFileSync('service.toml', 'utf8')); console.log(isDeepStrictEqual(a, JSON.parse(JSON.stringify(b)))); // true

The JSON5 version mirrors the shape of the data: you can see that timeouts sits inside server by looking at the braces. The TOML version is flatter. Every header names the full path from the root, so you can read any section on its own, but you assemble the tree in your head.

Structure icon

TOML Tables vs Nested Objects

A JSON5 object has one spelling: an opening brace, members, a closing brace. TOML offers three ways to write a table, and a file may use all of them.

Table headers

A line such as [server.timeouts] opens a table, and every following key belongs to it until the next header or the end of the file. Parent tables are created implicitly, so [x.y.z] works without first declaring [x]. The root table has no name and ends at the first header. That has a practical consequence: a top-level setting added at the bottom of a TOML file does not become a top-level setting. It joins whatever table was declared last.

Dotted keys

Writing physical.color = "orange" creates a table named physical. A key that really contains a dot must be quoted: "a.b" = 1 is a single key. In JSON5 there is no dotted-key syntax at all, so 'a.b': 1 can only mean one key with a dot in its name.

Inline tables

Braces exist in TOML too: point = { x = 1, y = 2 }. Under TOML 1.0.0, an inline table had to fit on one line. TOML 1.1.0 allows newlines and a trailing comma inside the braces. Either way the inline table is self-contained: once the closing brace is written, you cannot add keys to it from elsewhere in the file.

Redefinition rules

Because a table can be assembled from several places, TOML needs rules that stop two places from claiming it. Defining a key twice is invalid, declaring the same [table] header twice is invalid, and a table already created by dotted keys cannot be reopened with a header. Sub-tables of it can still be declared. JSON5 is looser: its specification says that when names in an object are not unique, the behavior of the receiving software is unpredictable. The JavaScript library keeps the last value.

JSON5.parse('{ a: 1, a: 2 }'); // { a: 2 } parse('a = 1\na = 2'); // TomlError: trying to redefine an already defined table or value parse('[a]\nx=1\n[a]\ny=2'); // TomlError: same reason

Unquoted keys differ

A bare TOML key may use only ASCII letters, digits, underscores and dashes, and 1234 = "value" is legal (the key is the string "1234"). An unquoted JSON5 key must be an ECMAScript 5.1 identifier name: it may contain $ and non-ASCII letters, but it cannot start with a digit or contain a dash. So build-system needs quotes in JSON5 and not in TOML. The syntax reference covers the identifier rules.

List icon

Arrays of Tables

The double-bracket header is TOML's most distinctive feature. Each [[workers]] appends a new table to the workers array. Any later reference to workers points at the most recently added element, which is how sub-tables and nested arrays attach to it.

[[fruits]] name = "apple" [fruits.physical] # belongs to apple color = "red" [[fruits.varieties]] # nested array inside apple name = "red delicious" [[fruits]] name = "banana" [[fruits.varieties]] # now belongs to banana name = "plantain"

The equivalent JSON5 shows ownership directly:

{ fruits: [ { name: 'apple', physical: { color: 'red' }, varieties: [{ name: 'red delicious' }], }, { name: 'banana', varieties: [{ name: 'plantain' }] }, ], }

Two edge cases are errors by specification. You cannot append with [[fruits]] to an array that was written statically as fruits = [], even though it is empty. And a child table cannot appear before the array element it belongs to has been defined. You can also skip headers and write an ordinary array of inline tables, such as points = [ { x = 1 }, { x = 2 } ]. TOML arrays, like JSON5 arrays, may mix value types and may carry comments between elements.

Number icon

Integers and Floats

TOML has separate integer and float types. JSON5, like JSON, has a single number production and leaves the in-memory type to the parser. The two grammars also accept different spellings. Each row below was checked against both libraries.

LiteralJSON5TOML
+1YesYes
.5 and 5.YesNo
0x1FYesYes
-0x1FYesNo
0o755 (octal) and 0b101 (binary)NoYes
1_000 (digit separators)NoYes
007 (leading zeros)NoNo
InfinityInfinity, +Infinity, -Infinityinf, +inf, -inf
Not a numberNaN, +NaN, -NaNnan, +nan, -nan

The special values are case-sensitive in both directions: inf is a syntax error in JSON5, and Infinity is invalid TOML.

Large integers

TOML 1.1.0 lets implementations support any integer size, recommends at least the signed 64-bit range handled losslessly, and requires an error when a value cannot be represented without loss. The JSON5 specification sets no such rule, and the JavaScript library returns an ordinary double, so precision can disappear without any message. This is the single most dangerous difference for IDs.

JSON5.parse('{ id: 9007199254740993 }'); // { id: 9007199254740992 } off by one, silently parse('id = 9007199254740993'); // TomlError: integer value cannot be represented losslessly parse('id = 9007199254740993', { integersAsBigInt: 'asNeeded' }); // { id: 9007199254740993n }

The limit belongs to the language and the library, not only to the format: Python's tomllib returns the same value exactly as an int. In JSON5 files, store large identifiers as strings. See data types for more.

The float that becomes an integer

JavaScript cannot tell 1.0 from 1. By default smol-toml turns a = 1.0 into a = 1 on a parse and re-serialize cycle, changing the TOML type. A consumer with a typed schema may reject the result. Parsing with integersAsBigInt: true and serializing with numbersAsFloat: true keeps the distinction.

Time icon

Native Dates and Times

TOML has four temporal types written without quotes, based on RFC 3339. JSON5 has none: a date is a string (or a number) that your program agrees to interpret.

TOML typeExampleMeaningPython tomllib result
Offset date-time1979-05-27T00:32:00-07:00A specific instantaware datetime.datetime
Local date-time1979-05-27T07:32:00Wall-clock date and time, no zonenaive datetime.datetime
Local date1979-05-27A whole daydatetime.date
Local time07:32:00A time of daydatetime.time

A space may replace the T. Parsers must support at least millisecond precision and truncate, not round, any extra digits. TOML 1.1.0 made seconds optional, so 07:32 is valid there and rejected by a 1.0.0 parser. TOML stores offsets, not named time zones such as Europe/Paris.

JavaScript has no native types matching the three local forms, so libraries must invent a mapping. smol-toml returns a TomlDate (a Date subclass) by default and can use the Temporal API instead. Its documentation warns that the legacy object accepts some impossible dates, and our test confirms it: d = 2026-02-30 parsed as March 2, 2026. Validate dates yourself if that matters.

Moving dates through JSON5 turns them into strings, and they stay strings on the way back:

const d = parse(`odt = 1979-05-27T00:32:00-07:00 ld = 1979-05-27 lt = 07:32:00`); const text = JSON5.stringify(d); // {odt:'1979-05-27T00:32:00.000-07:00',ld:'1979-05-27',lt:'07:32:00.000'} stringify(JSON5.parse(text)); // odt = "1979-05-27T00:32:00.000-07:00" // ld = "1979-05-27" // lt = "07:32:00.000"

To restore the types, convert known fields back to date objects before serializing, driven by a schema or an explicit list of keys. Guessing from the string's shape will eventually convert a value that was meant to be text.

Quote icon

Strings and Multi-Line Text

TOML has four string forms. Basic strings use double quotes and process escapes. Literal strings use single quotes and process nothing. Each has a triple-quoted multi-line version. JSON5 lets you pick single or double quotes, but both behave identically and both process escapes.

Multi-line strings

A JSON5 string may continue onto the next line only when the line ends with a backslash. The backslash and newline vanish from the value, and any indentation on the next line is kept. To get a line break in the value you still write \n. A raw newline inside quotes is a syntax error.

// JSON5 { sql: 'SELECT id \ FROM users', // "SELECT id FROM users" two: 'line one\n\ line two', // "line one\nline two" }

TOML's triple-quoted strings keep the newlines you type and drop one newline immediately after the opening delimiter. A backslash at the end of a line trims all whitespace up to the next visible character.

# TOML sql = """ SELECT id FROM users""" # "SELECT id\nFROM users" joined = """\ SELECT id \ FROM users""" # "SELECT id FROM users"

For embedded scripts, queries, templates and certificates, TOML is clearly easier to read. smol-toml writes multi-line values back as single-line strings with \n escapes, so a conversion round trip flattens that layout.

Backslashes and Windows paths

Literal strings are the other TOML advantage. In JSON5, an unrecognized escape such as \U yields the character itself, while \n and \t become a newline and a tab. A pasted Windows path therefore parses without error and comes out wrong.

JSON5.parse(String.raw`{ path: 'C:\Users\nodejs\temp' }`); // { path: 'C:Users\nodejs\temp' } backslash lost, newline and tab inserted parse(String.raw`path = 'C:\Users\nodejs\temp'`); // { path: 'C:\\Users\\nodejs\\temp' } exactly what was typed

In JSON5, double every backslash. Escape sets differ too: TOML 1.1.0 supports \e, \xHH, \uHHHH and \UHHHHHHHH and rejects unknown escapes, whereas JSON5 has no \e or \U form.

Forbidden icon

Null: TOML Has None

The list of TOML value types contains no null, and the specification says unspecified values are invalid. a = null fails to parse, and so does a key with nothing after the equals sign. The idiomatic way to say "not set" is to omit the key and let the application supply a default.

That is fine until absence and null mean different things, as in a layered config where an override file uses null to erase an inherited value. JSON5 keeps JSON's null and can express that. Serializers have to decide what to do, and smol-toml behaves differently for objects and arrays:

stringify(JSON5.parse('{ a: null, b: 1 }')); // 'b = 1\n' the key "a" is dropped without a warning stringify(JSON5.parse('{ a: [1, null] }')); // TypeError: arrays cannot contain null or undefined values

Sentinel values such as an empty string or -1 can stand in for null, but then every reader of the file must know the convention. Document it in a comment next to the key.

History icon

Specification Versions and Parser Support

JSON5 has one published specification version, 1.0.0. TOML has moved through several, among them 0.1.0 in March 2013, 0.4.0 in February 2015, 0.5.0 in July 2018, 1.0.0 in January 2021 and 1.1.0 in December 2025. The 1.1.0 additions that most affect files are:

  • Inline tables may span lines and end with a trailing comma.
  • Basic strings accept \xHH and \e escapes.
  • Seconds are optional in date-time and time values.

A file that uses any of these is invalid to a 1.0.0 parser, and a TOML file does not declare which version it targets. Check what your consumer supports:

ConsumerTOML support, as documented
Python logoPython tomllibAdded in 3.11 with TOML 1.0.0; 1.1.0 from Python 3.15 (released October 2026). Read only.
Rust logoCargoParses TOML 1.1 manifests and config files since Cargo 1.94 (March 2026)
Rust toml crateRelease 1.2.3 targets spec 1.1.0
Go logoGo github.com/BurntSushi/tomlTargets TOML 1.1.0
JavaScript logoJavaScript smol-tomlStates compliance with TOML 1.1.0

We ran the new syntax through Python 3.14.4 to show the failure mode: a multi-line inline table, a trailing comma inside braces, 07:32 and "\e" each raised TOMLDecodeError. If your project supports older runtimes, write 1.0.0 syntax. The Cargo changelog makes a similar point: using 1.1 features in Cargo.toml raises your development minimum supported Rust version, although the published manifest stays compatible with older parsers.

Globe icon

Ecosystem: Cargo, pyproject.toml and JSON Tooling

Format choice is often made for you. These two have settled in different places.

Cargo

Every Rust package has a Cargo.toml manifest. Single tables such as [package], [dependencies], [features] and [workspace] sit beside arrays of tables for build targets: [[bin]], [[example]], [[test]] and [[bench]]. The manifest format is TOML, so renaming it to .json5 is not an option. Rust programs can still read JSON5 for their own data, as covered in the Rust guide.

pyproject.toml

PEP 518, created in May 2016 and now final, chose TOML for Python's build configuration file. Its authors weighed the alternatives: JSON's syntax is awkward to edit by hand and has no comments, the YAML specification is large and unsafe loaders can execute code, and the INI-style configparser had no specification of what it accepted. The packaging documentation now describes the [build-system], [project], [dependency-groups] and [tool] tables. Python code that needs JSON5 uses a third-party package, described in the Python guide.

Where JSON5 fits

JSON5 lives closest to JavaScript. Its reference library mirrors the built-in JSON object with parse and stringify, ships a command-line converter, and any valid JSON file is already valid JSON5. That last property has no TOML equivalent: migrating from JSON to TOML means rewriting the file, while migrating to JSON5 means adding a comment. The project describes the format as meant for hand-written files such as configuration, not machine-to-machine communication. Neither format is read natively by every tool, so check the configuration guides before renaming any file.

Convert icon

Conversion Pitfalls

A converter that parses one format and serializes the other is two lines of code. The trouble is what those two lines do not report.

DirectionSource featureWhat happens
BothCommentsDiscarded by the parsers shown here
To TOMLnull propertySilently omitted
To TOMLnull in an arrayError
To TOMLTop-level array or scalarError: only an object can be serialized
To TOMLInteger beyond the safe rangeAlready rounded by the JSON5 parse, then written by smol-toml as a float: 9007199254740993 comes out as 9007199254740992.0
To TOMLKey order across values and tablesPlain values are written before tables
To TOMLHex numberWritten in decimal
From TOMLDate and time valuesBecome strings
From TOMLnan, infPreserved as NaN, Infinity; lost if you then use JSON.stringify, which writes null
From TOMLLarge integerError by default; if parsed as BigInt, json5 2.2.3 silently drops the property when serializing (null in an array)

A converter that refuses to lose data

This version checks the three silent or confusing cases before writing anything:

import JSON5 from 'json5'; import { stringify } from 'smol-toml'; function findProblems(value, path = '$', out = []) { if (value === null) { out.push(`${path}: null has no TOML equivalent`); } else if (Number.isInteger(value) && !Number.isSafeInteger(value)) { out.push(`${path}: integer outside the safe range, precision already lost`); } else if (typeof value === 'object') { for (const [k, v] of Object.entries(value)) findProblems(v, `${path}.${k}`, out); } return out; } export function toToml(text) { const data = JSON5.parse(text); if (data === null || typeof data !== 'object' || Array.isArray(data)) { throw new TypeError('TOML needs an object at the top level'); } const problems = findProblems(data); if (problems.length) throw new TypeError(problems.join('\n')); return stringify(data); }

Given { a: null, b: { id: 9007199254740993 } }, it throws with both problems listed:

$.a: null has no TOML equivalent $.b.id: integer outside the safe range, precision already lost

The range check is deliberately conservative: it also rejects a very large float written in exponent form, because after parsing the two look the same. For the service file at the top of this page, the function produces TOML with the same [server], [server.timeouts] and [[workers]] structure as the handwritten version, minus its comment. Always review a converted file by hand once and reinstate the comments. The conversion guide covers other target formats.

Target icon

Choosing: Where Each One Wins

Where TOML wins

  • Flat, sectioned settings. A file of headers and key = value lines has almost no punctuation to get wrong.
  • Dates and times. Schedules, release dates and expiry values are typed by the format.
  • Strictness. Duplicate keys and unknown escapes are errors rather than surprises.
  • Paths, regular expressions and embedded text. Literal and triple-quoted strings avoid escape noise.
  • Rust and Python projects. Cargo and Python packaging require it, and Python reads it from the standard library.

Where JSON5 wins

  • Deep or irregular nesting. Arrays inside objects inside arrays stay readable, while TOML headers grow long and order-sensitive.
  • JSON compatibility. Existing JSON parses unchanged, and values map one to one except Infinity and NaN, which JSON cannot hold.
  • Null and non-object roots. Test fixtures and data tables often need both.
  • Block comments for temporarily disabling a section.
  • Familiarity for anyone who writes JavaScript object literals.

A simple test: sketch your real config. If nearly everything fits under one or two levels of headings, TOML will read well. If you find yourself writing [[a.b.c]] and checking which element it attaches to, use braces. To try JSON5, start with your first config file.

Question icon

Common Questions

Is TOML a superset of JSON like JSON5 is?

No. A JSON document is not valid TOML: TOML uses =, requires a table at the top level and has no null. JSON5 accepts any valid JSON.

Can a TOML file hold a top-level array?

No. The root is always a table, so wrap the list under a key, for example with repeated [[item]] headers.

Can I convert TOML to JSON5 and back without changes?

Not in general. Comments disappear, dates become strings and, in JavaScript, floats with no fractional part can become integers. Data-only files without dates survive best.

Which one is faster to parse?

It depends on the parser and the document, and we have not benchmarked the two here. For configuration read once at startup, measure only if startup time is a real concern.

Does indentation matter in either format?

No. Both ignore indentation, so indenting TOML sub-tables is purely cosmetic and does not change which table a key belongs to.