Toml
写在前面
Toml 官网首页 的介绍已经足够快速上手.
如果需要详细的说明, 可以看看 官方文档.
这篇文档只作为笔记, 记录不常见的语法和容易出错的点.
Array of Tables
初见 toml 最疑惑的地方就是 "双层中括号", 因此放在文档开篇.
这被称之为 Array of Tables. 举例说明:
toml
[[products]]
name = "Hammer"
sku = 738594937
[[products]] # empty table within the array
[[products]]
name = "Nail"
sku = 284758393
color = "gray"以上对应的 json 文件:
json
{
"products": [
{ "name": "Hammer", "sku": 738594937 },
{ },
{ "name": "Nail", "sku": 284758393, "color": "gray" }
]
}数值类型
toml
# 可以使用 _ 使得数字更容易阅读.
int = 1_000
# 十六进制以 `0x` 开头
hex1 = 0xDEADBEEF
hex2 = 0xdeadbeef
hex3 = 0xdead_beef
# 八进制以 `0o` 开头
oct1 = 0o01234567
oct2 = 0o755 # useful for Unix file permissions
# 二进制以 `0b` 开头
bin1 = 0b11010110toml
# 可以使用科学计数法表示浮点数.
flt4 = 5e+22
flt6 = -2E-2
flt7 = 6.626e-34toml
sf1 = inf # positive infinity
sf2 = -inf # negative infinity
sf3 = nan # not a number字符串
toml
# 可以直接通过 "\u0000" 或 "\U00000000" 来输入 Unicode.
# 为了方便, 也提供了大多数语言所支持的 \t \n 等转移字符.
str3 = "Name\tJos\u00E9\nLoc\tSF."toml
# 单引号不会转义, 因此适合写入 " \ 等字符.
path = 'C:\Users\nodejs\templates'
# 如果使用双引号就需要写成这样, 显然不如单引号简单.
path = "C:\\Users\\nodejs\\templates"toml
# 以下两个值相等.
str1 = "The quick brown fox jumps over the lazy dog."
# 可以用这种方式输入较长的字符串.
str2 = """\
The quick brown \
fox jumps over \
the lazy dog.\
"""时间戳
RFC3339 定义了互联网中日期与时间的标准.
Toml 支持符合 RFC3339 标准的时间戳.
toml
# UTC 标准时间以 Z 作为结尾.
odt1 = 1979-05-27T07:32:00Z
# UTC+8 的表示方法.
odt2 = 1979-05-27T00:32:00+08:00
# 为了方便阅读, RFC3339 也允许将 T 替换成空格.
odt4 = 1979-05-27 07:32:00Z我们可以通过以下命令获取 RFC3339 标准的时间戳:
sh
# 默认会将日期与时间通过空格分隔.
date --rfc-3339=seconds
# 如果想用 T 来分隔日期与时间, 可以用此命令.
date --rfc-3339=seconds | tr ' ' 'T'键值对
可以通过 . 为 Table 内的项赋值.
toml
name = "Orange"
physical.color = "orange"
physical.shape = "round"
site."google.com" = true与上面结构对应的 json 文件:
json
{
"name": "Orange",
"physical": {
"color": "orange",
"shape": "round"
},
"site": {
"google.com": true
}
}数组
toml
integers = [ 1, 2, 3 ]
colors = [ "red", "yellow", "green" ]
nested_arrays_of_ints = [ [ 1, 2 ], [3, 4, 5] ]
nested_mixed_array = [ [ 1, 2 ], ["a", "b", "c"] ]
string_array = [ "all", 'strings', """are the same""", '''type''' ]
# Mixed-type arrays are allowed
numbers = [ 0.1, 0.2, 0.5, 1, 2, 5 ]
contributors = [
"Foo Bar <foo@example.com>",
{ name = "Baz Qux", email = "bazqux@example.com" }
]Table
Table 的规则与前面键值对的规则一样.
这里举个例子 (只是为了说明语法, 现实中多半不会这么写):
sh
[dog."tater.man"]
type.name = "pug"以上对应的 json 文件为:
json
{ "dog": { "tater.man": { "type": { "name": "pug" } } } }另外可以通过 Inline Table 来更紧凑的编写:
toml
name = { first = "Tom", last = "Preston-Werner" }
point = { x = 1, y = 2 }
animal = { type.name = "pug" }以上相当于:
toml
[name]
first = "Tom"
last = "Preston-Werner"
[point]
x = 1
y = 2
[animal]
type.name = "pug"