pythontoml

tomli-w, adding arrays from a python script


I have a toml file like this

[[fruits]]
fruit_property =x

[[fruits]]
fruit_property =x

[[fruits]]
fruit_property =x

And I want to encode this from a python script. So far in python i have done

fruits= [
 {'fruit_property':x},{'fruit_property':y},  {'fruit_property':z}, 
]

toml_string = tomli_w.dumps(fruits)

and then writing the string to a file. However, this doesn't convert the array of dicts, and instead just keeps them the same way my code has them. I've looked and can't find any documentation for this, has anyone run into similar issues?

However, this does not convert


Solution

  • Seems like a bug in tomli-w (even after adding an outer "fruits" key).

    I suggest you to dumps your fruits object with tomlkit (!pip install tomlkit) :

    import tomlkit
    
    fruits = [
        {"fruit_property": "x"}, {"fruit_property": "y"}, {"fruit_property": "z"},
    ]
    
    toml_string = tomlkit.dumps({"fruits": fruits})
    

    Output :

    print(toml_string)
    
    [[fruits]]
    fruit_property = "x"
    
    [[fruits]]
    fruit_property = "y"
    
    [[fruits]]
    fruit_property = "z"