c++yamlyaml-cpp

How to manually override the automatic quotation of strings


I am writing to a YAML file with jbeders/yaml-cpp and I am writing IP addresses to a file. When I write the wildcard IP "*" to the file, it automatically gets quoted (since '*' is a special character in YAML). But when I want to write the IP 10.0.1.1, it does not get quoted.

This is how I assign the node for the asterix:

ip_map["ip"] = "*"; 

This is how I assign the node for the numerical IP:

ip_map["ip"] = "10.0.0.1"; 

This is the resulting file that gets emitted with defaults (yaml_out << ip_map;)

ip: "*"
ip: 10.0.1.1

I have tried setting the emitter format option like this:

YAML::Emitter yaml_out;
yaml_out.SetStringFormat(YAML::DoubleQuoted);

... but this seems to double quote everything like this:

"ip": "*"
"ip": "10.0.1.1"

How do I consistently double quote all string values and not the keys or other numerical/boolean values?

EDIT: I dumbed down the question a little and used literals instead of a variable.

Let's say I wanted instead to have a node like this:

fileA:

original_ip: "10.0.0.1"

Which I then read in with doc = YAML::LoadFile("fileA");. I then use the value from that file and try assign it to the original ip_map["ip"], however I want to force double quotes around the IP address.

So the full snippet would look like this:

ip_map["ip"] = doc["original"].as<std::string>();

How do I force the ip_map node's assigned string value (10.0.0.1) to be emitted with double quotes?


Solution

  • You should edit your question for conciseness, such as 'Using the yaml-cpp, how to serialize a map not quoting its keys but quoting its values?'.

    To the point, you should manually iterate a map alternating string formats like the following.

    yaml_out << YAML::BeginMap;
    for (auto p : ip_map) {
        yaml_out << p.first;
        yaml_out.SetStringFormat(YAML::DoubleQuoted);
        yaml_out << p.second;
        yaml_out.SetStringFormat(YAML::Auto);
    }
    yaml_out << YAML::EndMap;