← Runnable Projects

阅读中文版本

TOML to JSON Converter

A Node CLI that parses a minimal TOML subset (tables, key-values, strings, numbers, booleans) and prints the equivalent JSON.

intermediatejavascriptunverified

Project

node-toml-to-json

Entry point: toml-to-json.mjs

Install

node --version

Run

node toml-to-json.mjs config.toml

Test

node --test toml.test.mjs

Expected output

Reads a TOML file and writes the parsed object as indented JSON; a top-level title key becomes a JSON string field.

Dependencies

  • node >=20

What it does

Parses tables, dotted keys, strings, integers, floats, and booleans into a plain object. It is intentionally a subset and reports the line number when it meets syntax it does not support.

import { readFileSync } from 'node:fs';

export function parseToml(text) {
  const root = {};
  let current = root;
  for (const [i, raw] of text.split(/\r?\n/).entries()) {
    const line = raw.replace(/#.*$/, '').trim();
    if (!line) continue;
    const section = line.match(/^\[([^\]]+)\]$/);
    if (section) {
      current = section[1].split('.').reduce((o, k) => (o[k] ??= {}), root);
      continue;
    }
    const kv = line.match(/^([\w.-]+)\s*=\s*(.+)$/);
    if (!kv) throw new Error('unsupported syntax at line ' + (i + 1));
    const [, key, rawVal] = kv;
    current[key] = parseValue(rawVal.trim());
  }
  return root;
}

function parseValue(v) {
  if (/^".*"$/.test(v)) return v.slice(1, -1);
  if (v === 'true' || v === 'false') return v === 'true';
  if (/^-?\d+$/.test(v)) return parseInt(v, 10);
  if (/^-?\d+\.\d+$/.test(v)) return parseFloat(v);
  throw new Error('unsupported value: ' + v);
}

const file = process.argv[2];
if (!file) { console.error('usage: toml-to-json <file.toml>'); process.exit(1); }
console.log(JSON.stringify(parseToml(readFileSync(file, 'utf8')), null, 2));

Run and verify

node toml-to-json.mjs config.toml

Run the test command to check the implementation: node --test toml.test.mjs.

Expected Output

For a file containing title = “demo” and a [server] table with port = 8080, the output is valid JSON:

{
  "title": "demo",
  "server": {
    "port": 8080
  }
}

Limitations

Supports a deliberate subset only: arrays, inline tables, dates, and multi-line strings are not parsed and raise an error instead of being misread.