Search code examples
yaml-cpp

Can't Emit an Empty Value with yaml-cpp


I would like to emit an empty value but when I assign an empty string to be emitted the output is not technically empty.

Code Snippet:

YAML::Emitter out;
std::string name;
out << YAML::Key << "name";
out << YAML::Value << name;

Expected yaml Output:

name:

Actual yaml Output:

name: ""

As you can see I have an empty string defined and I expect the yaml output to effectively be empty. Is this intended behavior? If so is there a way to work around this? I'm aiming to have my entire yaml output be quote free.


Solution

  • The YAML

    name:
    

    doesn't have a string value for the key name; it's actually a null value. See, e.g., an online parser here; the canonical YAML representation is:

    !!map {
      ? !!str "name"
      : !!null "null",
    }
    

    yaml-cpp is trying to ensure that what you told it ("write this empty string") is how the resulting YAML will be parsed, so it's writing the empty string as "".

    If you want to write a null value, then either don't write a value, or write YAML::Null. The latter (I believe) will produce

    name: ~
    

    which is the canonical form of null.