9

我想从 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 to TOML 转换器似乎不适用于我的示例。它是否适用于数组/表数组的更深嵌套?

4

2 回答 2

7

根据在主 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" }
  ]
}
于 2020-03-07T13:39:14.757 回答
3

我不确定为什么它以前不起作用,但这似乎有效:

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"
    }]
}
于 2018-02-26T23:05:39.327 回答