Home > Software engineering >  How to manually override the automatic quotation of strings
How to manually override the automatic quotation of strings

Time:09-16

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?

CodePudding user response:

‘*’ is a special character in YAML (it’s a way to dereference an alias), so yaml-cpp quotes it to avoid ambiguity.

CodePudding user response:

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

To the point, you should manually iterate a map alternating the string format 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;
  • Related