Udi
Udi

Reputation: 30532

tomlkit: nicely formatted array with inline tables

I am trying to use tomlkit 0.8.0 to create a TOML from the following data:

data = {
    'stuff': [
        {'a':1, 'b': 2},
        {'c': 3},
        {'a': 4},
    ]
}

in this format exactly:

stuff = [
    {a = 1, b = 2},
    {c = 3},
    {a = 4}, 
]

A simpleprint(tomlkit.dumps(data)) creates:

[[stuff]]
a = 1
b = 2

[[stuff]]
c = 3

[[stuff]]
a = 4

How can this be done is a simple way?

Upvotes: 1

Views: 1801

Answers (2)

simon
simon

Reputation: 5476

The following works with tomlkit 0.11 (and probably earlier):

doc = tomlkit.document()
a = tomlkit.array()
for x in data['stuff']:
    t = tomlkit.inline_table()
    t.update(x)
    a.add_line(t)
doc.add('stuff', a.multiline(True))
print(tomlkit.dumps(doc))

Using a.multiline(True) will return the array in its multiline version. Unlike explicitly adding a new line via tomlkit.nl(), there will not be an empty line between the last array entry and its closing bracket, so it should exactly match the required format.

Upvotes: 0

Udi
Udi

Reputation: 30532

The best I have found so far is somewhat complicated:

doc = tomlkit.document()
a = tomlkit.array()
for x in data['stuff']:
    t = tomlkit.inline_table()
    t.update(x)
    a.add_line(t)
a.append(tomlkit.nl())
doc.add('stuff', a)
print(tomlkit.dumps(doc))

Upvotes: 0

Related Questions