TOML是否支持对象/表的嵌套数组?

17

我想从 TOML 文件中生成 JSON。JSON 结构应该是这样的,数组内有对象,而这些对象又在一个数组内:

{
    "things": [
        {
            "a": "thing1",
            "b": "fdsa",
            "multiline": "Some sample text."
        },
        {
            "a": "Something else",
            "b": "zxcv",
            "multiline": "Multiline string",
            "objs": [  // LOOK HERE
                { "x": 1},
                { "x": 4 },
                { "x": 3 }
            ]
        },
        {
            "a": "3",
            "b": "asdf",
            "multiline": "thing 3.\nanother line"
        }
    ]
}

我有一些 TOML,看起来像下面的例子,但似乎不能与objs部分一起使用。

name = "A Test of the TOML Parser"

[[things]]
a = "thing1"
b = "fdsa"
multiLine = """
Some sample text."""

[[things]]
a = "Something else"
b = "zxcv"
multiLine = """
Multiline string"""
[[things.objs]]  # MY QUESTION IS ABOUT THIS PART
x = 1
[[things.objs]]
x = 4
[[things.objs]]
x = 3

[[things]]
a = "3"
b = "asdf"
multiLine = """
thing 3.
another line"""
有没有一种方法可以在TOML中实现它?JSON到TOML的转换器似乎不能处理我的示例。它是否适用于更深层次的数组/表的嵌套?
2个回答

21

根据合并此功能的主TOML存储库中的PR,这是对象数组的正确语法:

[[products]]
name = "Hammer"
sku = 738594937

[[products]]

[[products]]
name = "Nail"
sku = 284758393
color = "gray"

这将生成以下等效的JSON:

{
  "products": [
    { "name": "Hammer", "sku": 738594937 },
    { },
    { "name": "Nail", "sku": 284758393, "color": "gray" }
  ]
}

13
我不确定之前为什么不起作用,但是这似乎可以正常工作:
name = "A Test of the TOML Parser"

[[things]]
a = "thing1"
b = "fdsa"
multiLine = """
Some sample text."""

[[things]]
a = "Something else"
b = "zxcv"
multiLine = """
Multiline string"""
[[things.objs]]
x = 1
[[things.objs]]
x = 4
[[things.objs]]
x = 7
[[things.objs.morethings]]
y = [
    2,
    3,
    4
]
[[things.objs.morethings]]
y = 9

[[things]]
a = "3"
b = "asdf"
multiLine = """
thing 3.
another line"""

JSON输出:

{
    "name": "A Test of the TOML Parser",
    "things": [{
        "a": "thing1",
        "b": "fdsa",
        "multiLine": "Some sample text."
    }, {
        "a": "Something else",
        "b": "zxcv",
        "multiLine": "Multiline string",
        "objs": [{
            "x": 1
        }, {
            "x": 4
        }, {
            "x": 7,
            "morethings": [{
                "y": [2, 3, 4]
            }, {
                "y": 9
            }]
        }]
    }, {
        "a": "3",
        "b": "asdf",
        "multiLine": "thing 3.\\nanother line"
    }]
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接