Home > Blockchain >  libyaml: retrieve the key of the root element
libyaml: retrieve the key of the root element

Time:11-08

Given this simple YAML example:

{CR: {ab: 12}}

I want to retrieve CR. Perhaps I don't know the correct word to identify the "root key", hence I didn't find anything useful. I use QtYaml that is based upon libyaml, in Ubuntu 20.04.

QString yaml = "{CR: {ab: 12}}";
YAML::Node root = YAML::Load(yaml.toStdString().c_str());

QString key;
YAML::convert<QString>().decode(root, key);
qDebug() << key;

It returns an empty string. What I have to do in order to have key = "CR"?

CodePudding user response:

This is not libyaml; libyaml doesn't have a C interface with namespaces. Judging by the look of the API calls, you're using .

YAML documents have a root node, in your case this is a mapping. A mapping is a collection node and thus doesn't properly convert into a string. What you want is to extract the fist key of that mapping:

root.begin()->first.as<QString>();

begin() returns an iterator over the root mappings key-value pairs. -> dereferences to its first item. first retrieves the key. as<QString>() converts the key to QString and returns it.

  • Related