Featured

TOML vs JSON: Complete Comparison and Node.js Usage Guide

T
Team
·18 min read
#toml#json#nodejs#configuration#file formats#backend

TOML vs JSON: Complete Comparison and Node.js Usage Guide


Configuration files are essential in modern development. Two popular formats, TOML and JSON, serve different purposes and have distinct advantages. This guide will help you understand when to use each format and how to work with them in Node.js.


What is TOML?


TOML (Tom's Obvious, Minimal Language) is a configuration file format designed to be easy to read and write. It was created by Tom Preston-Werner, co-founder of GitHub.


TOML Example


toml(30 lines, showing 15)
1# config.toml
2title = "My Application"
3version = "1.0.0"
4 
5[database]
6host = "localhost"
7port = 5432
8username = "admin"
9password = "secret123"
10ssl = true
11 
12[server]
13host = "0.0.0.0"
14port = 3000
15timeout = 30

What is JSON?


JSON (JavaScript Object Notation) is a lightweight data-interchange format that's widely used for APIs, configuration files, and data storage.


JSON Example


json(33 lines, showing 15)
1{
2 "title": "My Application",
3 "version": "1.0.0",
4 "database": {
5 "host": "localhost",
6 "port": 5432,
7 "username": "admin",
8 "password": "secret123",
9 "ssl": true
10 },
11 "server": {
12 "host": "0.0.0.0",
13 "port": 3000,
14 "timeout": 30
15 },

Key Differences


1. Readability


TOML:

  • More human-readable
  • Supports comments
  • Better for configuration files
  • Easier to edit manually

  • JSON:

  • Less readable for complex nested structures
  • No comments (though some parsers support them)
  • More verbose
  • Better for programmatic generation

  • 2. Data Types


    TOML Supports:

  • Strings, integers, floats, booleans
  • Dates and times
  • Arrays and tables
  • Inline tables
  • Array of tables

  • JSON Supports:

  • Strings, numbers, booleans
  • Arrays
  • Objects
  • null

  • 3. Comments


    TOML:

    toml
    1# This is a comment
    2name = "value" # Inline comment

    JSON:

    json
    1{
    2 // Comments are not officially supported
    3 "name": "value"
    4}

    4. Use Cases


    TOML is better for:

  • Configuration files (Cargo.toml, pyproject.toml, package.json alternatives)
  • Human-edited settings
  • Documentation in code
  • CI/CD configuration

  • JSON is better for:

  • API responses
  • Data exchange between services
  • Programmatically generated files
  • Web applications
  • NoSQL databases

  • Working with TOML in Node.js


    Installation


    bash
    1npm install @iarna/toml
    2# or
    3npm install toml

    Using @iarna/toml (Recommended)


    javascript(27 lines, showing 15)
    1const fs = require('fs');
    2const TOML = require('@iarna/toml');
    3 
    4// Reading TOML file
    5try {
    6 const tomlContent = fs.readFileSync('config.toml', 'utf-8');
    7 const config = TOML.parse(tomlContent);
    8
    9 console.log(config.title);
    10 console.log(config.database.host);
    11 console.log(config.users);
    12} catch (error) {
    13 console.error('Error parsing TOML:', error);
    14}
    15 

    Complete TOML Example


    javascript(55 lines, showing 15)
    1// config-loader.js
    2const fs = require('fs');
    3const path = require('path');
    4const TOML = require('@iarna/toml');
    5 
    6class ConfigLoader {
    7 constructor(configPath) {
    8 this.configPath = configPath;
    9 this.config = null;
    10 }
    11 
    12 load() {
    13 try {
    14 const content = fs.readFileSync(this.configPath, 'utf-8');
    15 this.config = TOML.parse(content);

    Working with JSON in Node.js


    Native JSON Support


    javascript(25 lines, showing 15)
    1const fs = require('fs');
    2 
    3// Reading JSON file
    4try {
    5 const jsonContent = fs.readFileSync('config.json', 'utf-8');
    6 const config = JSON.parse(jsonContent);
    7
    8 console.log(config.title);
    9 console.log(config.database.host);
    10} catch (error) {
    11 console.error('Error parsing JSON:', error);
    12}
    13 
    14// Writing JSON file
    15const config = {

    Advanced JSON Handling


    javascript(96 lines, showing 15)
    1// json-utils.js
    2const fs = require('fs').promises;
    3const path = require('path');
    4 
    5class JSONConfigManager {
    6 constructor(configPath) {
    7 this.configPath = configPath;
    8 this.config = null;
    9 }
    10 
    11 async load() {
    12 try {
    13 const content = await fs.readFile(this.configPath, 'utf-8');
    14 this.config = JSON.parse(content);
    15 return this.config;

    Converting Between TOML and JSON


    TOML to JSON


    javascript(16 lines, showing 15)
    1const fs = require('fs');
    2const TOML = require('@iarna/toml');
    3 
    4function tomlToJson(tomlPath, jsonPath) {
    5 try {
    6 const tomlContent = fs.readFileSync(tomlPath, 'utf-8');
    7 const parsed = TOML.parse(tomlContent);
    8 const jsonString = JSON.stringify(parsed, null, 2);
    9 fs.writeFileSync(jsonPath, jsonString);
    10 console.log('Converted TOML to JSON successfully');
    11 } catch (error) {
    12 console.error('Conversion error:', error);
    13 }
    14}
    15 

    JSON to TOML


    javascript(16 lines, showing 15)
    1const fs = require('fs');
    2const TOML = require('@iarna/toml');
    3 
    4function jsonToToml(jsonPath, tomlPath) {
    5 try {
    6 const jsonContent = fs.readFileSync(jsonPath, 'utf-8');
    7 const parsed = JSON.parse(jsonContent);
    8 const tomlString = TOML.stringify(parsed);
    9 fs.writeFileSync(tomlPath, tomlString);
    10 console.log('Converted JSON to TOML successfully');
    11 } catch (error) {
    12 console.error('Conversion error:', error);
    13 }
    14}
    15 

    Real-World Examples


    Example 1: Express.js Configuration


    Using TOML (config.toml):


    toml(21 lines, showing 15)
    1[app]
    2name = "My Express App"
    3env = "production"
    4port = 3000
    5 
    6[database]
    7type = "postgresql"
    8host = "localhost"
    9port = 5432
    10name = "mydb"
    11user = "admin"
    12password = "secret"
    13 
    14[redis]
    15host = "localhost"

    Using JSON (config.json):


    json(24 lines, showing 15)
    1{
    2 "app": {
    3 "name": "My Express App",
    4 "env": "production",
    5 "port": 3000
    6 },
    7 "database": {
    8 "type": "postgresql",
    9 "host": "localhost",
    10 "port": 5432,
    11 "name": "mydb",
    12 "user": "admin",
    13 "password": "secret"
    14 },
    15 "redis": {

    Loading in Express.js:


    javascript
    1// Using TOML
    2const TOML = require('@iarna/toml');
    3const fs = require('fs');
    4const config = TOML.parse(fs.readFileSync('config.toml', 'utf-8'));
    5 
    6// Using JSON
    7const config = require('./config.json');
    8 
    9// Express app setup
    10const express = require('express');
    11const app = express();
    12 
    13app.listen(config.app.port, () => {
    14 console.log(`${config.app.name} running on port ${config.app.port}`);
    15});

    Example 2: Environment-Specific Configuration


    javascript(30 lines, showing 15)
    1// config-loader.js
    2const fs = require('fs');
    3const TOML = require('@iarna/toml');
    4 
    5function loadConfig(env = 'development') {
    6 const configPath = `config.${env}.toml`;
    7
    8 if (!fs.existsSync(configPath)) {
    9 throw new Error(`Config file ${configPath} not found`);
    10 }
    11
    12 const content = fs.readFileSync(configPath, 'utf-8');
    13 const config = TOML.parse(content);
    14
    15 // Override with environment variables

    Example 3: Package Configuration


    package.toml (alternative to package.json):


    toml(18 lines, showing 15)
    1[package]
    2name = "my-project"
    3version = "1.0.0"
    4description = "My awesome project"
    5main = "index.js"
    6 
    7[scripts]
    8start = "node index.js"
    9test = "jest"
    10build = "webpack"
    11 
    12[dependencies]
    13express = "^4.18.0"
    14lodash = "^4.17.21"
    15 

    Performance Comparison


    Parsing Speed


    javascript(27 lines, showing 15)
    1const fs = require('fs');
    2const TOML = require('@iarna/toml');
    3 
    4// Benchmark function
    5function benchmark(name, fn, iterations = 1000) {
    6 const start = process.hrtime.bigint();
    7 for (let i = 0; i < iterations; i++) {
    8 fn();
    9 }
    10 const end = process.hrtime.bigint();
    11 const duration = Number(end - start) / 1000000; // Convert to milliseconds
    12 console.log(`${name}: ${duration.toFixed(2)}ms (${(duration / iterations).toFixed(4)}ms per operation)`);
    13}
    14 
    15// Test files

    Results:

  • JSON parsing is typically faster (native support)
  • TOML parsing is slightly slower but still very fast
  • For most applications, the difference is negligible

  • When to Use Each Format


    Use TOML When:

  • ✅ Configuration files that humans need to edit
  • ✅ Documentation needs to be embedded
  • ✅ Comments are important
  • ✅ Working with Rust, Python, or other TOML-native ecosystems
  • ✅ CI/CD configuration files
  • ✅ Project metadata (like Cargo.toml)

  • Use JSON When:

  • ✅ API responses and requests
  • ✅ Data exchange between services
  • ✅ Programmatically generated files
  • ✅ Web applications (browser-native support)
  • ✅ NoSQL databases
  • ✅ When comments aren't needed
  • ✅ When maximum compatibility is required

  • Best Practices


    TOML Best Practices


    toml(19 lines, showing 15)
    1# Use comments to document configuration
    2# Database connection settings
    3[database]
    4# PostgreSQL connection string
    5host = "localhost"
    6port = 5432
    7 
    8# Use tables for logical grouping
    9[server.production]
    10port = 8080
    11 
    12[server.development]
    13port = 3000
    14 
    15# Use arrays for multiple values

    JSON Best Practices


    json
    1{
    2 "version": "1.0.0",
    3 "config": {
    4 "database": {
    5 "host": "localhost",
    6 "port": 5432
    7 }
    8 },
    9 "features": {
    10 "enabled": [
    11 "auth",
    12 "logging"
    13 ],
    14 "disabled": [
    15 "debug"
    16 ]
    17 }
    18}

    Migration Guide


    Migrating from JSON to TOML


    javascript
    1// migrate-to-toml.js
    2const fs = require('fs');
    3const TOML = require('@iarna/toml');
    4 
    5function migrateJsonToToml(jsonPath, tomlPath) {
    6 const jsonContent = fs.readFileSync(jsonPath, 'utf-8');
    7 const jsonData = JSON.parse(jsonContent);
    8 const tomlContent = TOML.stringify(jsonData);
    9 fs.writeFileSync(tomlPath, tomlContent);
    10 console.log(`Migrated ${jsonPath} to ${tomlPath}`);
    11}
    12 
    13migrateJsonToToml('package.json', 'package.toml');

    Migrating from TOML to JSON


    javascript
    1// migrate-to-json.js
    2const fs = require('fs');
    3const TOML = require('@iarna/toml');
    4 
    5function migrateTomlToJson(tomlPath, jsonPath) {
    6 const tomlContent = fs.readFileSync(tomlPath, 'utf-8');
    7 const tomlData = TOML.parse(tomlContent);
    8 const jsonContent = JSON.stringify(tomlData, null, 2);
    9 fs.writeFileSync(jsonPath, jsonContent);
    10 console.log(`Migrated ${tomlPath} to ${jsonPath}`);
    11}
    12 
    13migrateTomlToJson('config.toml', 'config.json');

    Conclusion


    Both TOML and JSON have their place in modern development:


  • TOML excels at human-readable configuration files with comments and better readability
  • JSON is the standard for APIs, data exchange, and web applications

  • Key Takeaways:

  • Use TOML for configuration files that need comments and human editing
  • Use JSON for APIs, data exchange, and when you need native browser support
  • Both formats work well in Node.js with appropriate libraries
  • Performance differences are minimal for most use cases
  • Choose based on your specific needs and team preferences

  • For Node.js applications, you can use both formats effectively. TOML is great for application configuration, while JSON remains the standard for APIs and data exchange.


    Additional Resources


  • [TOML Specification](https://toml.io/)
  • [@iarna/toml npm package](https://www.npmjs.com/package/@iarna/toml)
  • [JSON Specification](https://www.json.org/)
  • [Node.js fs module](https://nodejs.org/api/fs.html)

  • Happy coding!


    Enjoyed this article?

    Support our work and help us create more free content for developers.

    Stay Updated

    Get the latest articles and updates delivered to your inbox.