How to modify toml file in cpp (TOML++)

Viewed 156

I am using toml++. How can I modify a particular value of a TOML file in CPP using toml++

json ConfigService::getAllData(std::string filePath)
{
    try
    {
        auto _data_table = toml::parse_file(filePath);
        _data_table["config_paths"]["DIAAI_core"] = "diaaiSetting.toml";  # this is not working
        cout << _data_table << endl;
    }
    catch (const exception err)
    {
        std::cerr << "Parsing failed:\n"
                  << err.what() << "\n";
        std::runtime_error(err.what());
    }
}

traceback

error: no match for ‘operator=’ (operand types are ‘toml::v3::node_view<toml::v3::node>’ and ‘int’)
   51 |         _data_table["config_paths"] = 1;
1 Answers

For a few days, I had this issue as well and looked into many ways of trying to set values using toml++. What I've come up with can be a temporary solution, but it works pretty decently.

#include <iostream>
#include <toml++/toml.hpp>
using namespace std::string_view_literals;

int main() {
    static constexpr auto source = R"(
        [config_paths]
        DIAAI_core = [""]
    )"sv;
    toml::table _data_table      = toml::parse(source);

    if (toml::array* arr = _data_table["config_paths"]["DIAAI_core"].as_array()) {
        arr->for_each([](auto&& el) {
            if constexpr (toml::is_string<decltype(el)>)
                if(el == "")
                    el = "diaaiSetting.toml"sv;
        });
    }
    std::cout << _data_table << std::endl; 
    return 0;
}

output: 
[config_paths]
DIAAI_core = [ 'diaaiSetting.toml' ]

The value itself is not a string, but an array of strings that just holds one value, so deserializing it should be fairly easy.

You can interact with values easily in toml11 so you may want to take a look at that if this does not suit you.

Related