TOML是否支持对象/表的嵌套数组?嵌套结构转JSON方法问询
Hey there! Let's tackle your TOML-related questions clearly and with practical examples:
1. Does TOML support nested arrays of objects/tables?
Absolutely! Nested arrays of tables (TOML’s term for "objects") is a core feature of the specification. You can nest arrays of tables as deeply as you need—there’s no hard limit on nesting depth.
2. How to write valid TOML for nested arrays of objects (to generate your target JSON)?
It sounds like your previous attempt had syntax issues with the objs section. Let’s walk through two valid approaches to create the nested structure you want, using a sample target JSON as reference first:
Example Target JSON
Suppose this is the structure you’re aiming for:
{ "data": { "objs": [ { "title": "First Object", "sub_items": [ { "id": 1, "content": "Nested Item 1" }, { "id": 2, "content": "Nested Item 2" } ] }, { "title": "Second Object", "sub_items": [ { "id": 3, "content": "Nested Item 3" } ] } ] } }
Approach 1: Inline Table Arrays (Compact Syntax)
If you prefer a concise style, use inline tables inside arrays:
[data] objs = [ { title = "First Object", sub_items = [ { id = 1, content = "Nested Item 1" }, { id = 2, content = "Nested Item 2" } ] }, { title = "Second Object", sub_items = [ { id = 3, content = "Nested Item 3" } ] } ]
Approach 2: Expanded Array Tables (Readable for Complex Structures)
For larger or more complex nested structures, use TOML’s array table syntax ([[...]]), which makes the hierarchy explicit:
[data] # Add first object to the objs array [[data.objs]] title = "First Object" # Add nested items to this object's sub_items array [[data.objs.sub_items]] id = 1 content = "Nested Item 1" [[data.objs.sub_items]] id = 2 content = "Nested Item 2" # Add second object to the objs array [[data.objs]] title = "Second Object" [[data.objs.sub_items]] id = 3 content = "Nested Item 3"
Both snippets will convert to the target JSON correctly. The key is using [[...]] to denote array entries: each [[data.objs]] appends a new object to the objs array, and [[data.objs.sub_items]] appends to the sub_items array of the most recently defined objs entry.
Confirmation on Deep Nesting
TOML fully supports even deeper levels of nesting. For example, you could extend the example to add a third layer:
[[data.objs]] title = "Third Object" [[data.objs.sub_items]] id = 4 content = "Nested Item 4" [[data.objs.sub_items.sub_sub_items]] detail = "Deepest nested item"
This translates to a JSON structure with a three-level nested array of objects.
内容的提问来源于stack exchange,提问作者R891

