什么是 JSON 转 TOML 转换?
JSON 转 TOML 转换是将 JavaScript Object Notation 格式的数据转换为 Tom's Obvious Minimal Language 格式的过程。JSON 使用花括号、方括号和带引号的键来表示结构化数据。TOML 使用扁平的键值语法和节头(称为表),读起来像 INI 文件,但具有严格的类型定义。TOML 专门为配置文件设计,在这类场景中,人类可读性比机器数据交换更为重要。
TOML 已成为 Rust(Cargo.toml)、Python 打包(pyproject.toml)、Hugo 静态站点、Netlify 部署配置以及众多 CLI 工具的默认配置格式。当你的源数据以 JSON 形式存在——来自 API 响应、导出的配置或生成的文件——而目标系统需要 TOML 时,你需要一个能将 JSON 对象映射为 TOML 表、将 JSON 数组映射为 TOML 数组,并准确保留每种数据类型的转换工具。
在线将 JSON 转换为 TOML 是从现有 JSON 数据生成有效 TOML 最快捷的方式。转换会自动处理类型映射:JSON 字符串变为 TOML 字符串,JSON 数字变为 TOML 整数或浮点数,JSON 布尔值直接对应,JSON 对象变为 TOML 表。唯一的例外是 null——TOML 没有 null 类型,因此 null 值会被省略,或根据转换器的处理方式转换为空字符串。
为什么使用这个 JSON 转 TOML 转换器?
配置文件需要 TOML,而 API 和工具输出的是 JSON。这个转换器弥合了两种格式之间的差距,让你无需手动重写即可在二者之间迁移数据。
JSON 转 TOML 使用场景
JSON 与 TOML 对比
JSON 和 TOML 在功能上有重叠,但在语法、类型支持和预期用途上存在差异。下表展示了影响转换结果的主要区别。
| 特性 | JSON | TOML |
|---|---|---|
| Syntax | Braces, brackets, colons, commas | Key = value, [table], [[array]] |
| Comments | Not allowed (RFC 8259) | Supported with # |
| Data types | string, number, boolean, null, object, array | string, integer, float, boolean, datetime, array, table |
| null support | Native (null) | No null type — omit the key or use empty string |
| Nested objects | Unlimited nesting depth | Dotted keys or [table.subtable] headers |
| Arrays of objects | Array of objects with [] | [[array-of-tables]] syntax |
| Readability | Moderate — bracket-heavy at depth | High — flat key-value pairs |
| Spec | RFC 8259 / ECMA-404 | TOML v1.0.0 (toml.io) |
TOML 转换注意事项
TOML 有一些与 JSON 不同的规则,会影响转换输出。以下四个问题是最容易引起混淆的地方。
代码示例
以编程方式将 JSON 转换为 TOML 在大多数语言中都需要 TOML 序列化库。标准库负责 JSON 解析,TOML 输出则需要专用包。
import { stringify } from '@iarna/toml'
const json = '{"title":"My App","database":{"host":"localhost","port":5432}}'
const obj = JSON.parse(json)
const toml = stringify(obj)
console.log(toml)
// → title = "My App"
// →
// → [database]
// → host = "localhost"
// → port = 5432import json
import tomli_w # pip install tomli_w
json_str = '{"title": "My App", "database": {"host": "localhost", "port": 5432}}'
data = json.loads(json_str)
toml_str = tomli_w.dumps(data)
print(toml_str)
# → title = "My App"
# →
# → [database]
# → host = "localhost"
# → port = 5432package main
import (
"encoding/json"
"fmt"
"github.com/pelletier/go-toml/v2"
)
func main() {
jsonStr := `{"title":"My App","database":{"host":"localhost","port":5432}}`
var data map[string]interface{}
json.Unmarshal([]byte(jsonStr), &data)
tomlBytes, _ := toml.Marshal(data)
fmt.Println(string(tomlBytes))
// → title = 'My App'
// →
// → [database]
// → host = 'localhost'
// → port = 5432
}# Using yj (https://github.com/sclevine/yj)
echo '{"title":"My App","port":3000}' | yj -jt
# → title = "My App"
# → port = 3000
# Using remarshal (pip install remarshal)
echo '{"title":"My App","port":3000}' | remarshal -if json -of toml
# → title = "My App"
# → port = 3000