1

I am attempting to use yaml-cpp to process the following yaml:

- hosts: localhost
  tasks:
    - shell: whoami
    - shell: hostname

I have a constraint that I do not control the yaml coming in. It seems overly complex to me, but I have to process that.

Looking at http://yaml-online-parser.appspot.com/?yaml=-+hosts%3A+localhost%0A++tasks%3A%0A++++-+shell%3A+whoami%0A++++-+shell%3A+hostname&type=canonical_yaml

shows the yaml as good.

I am using the following code to try to get to the tasks:

YAML::Node pb = YAML::LoadFile(str_pbFilename);

printNodeInfo(pb);

if (pb.Type() == YAML::NodeType::Sequence)
{
    int count = 0;
    for (YAML::const_iterator it = pb.begin(); it != pb.end(); ++it)
    {
        if (it->first)
        {
            cout << "found first" << endl;
        }
        count++;
        cout << "count = " << count << endl;
    }
}

exception when I attempt to access anything it-> related (first or second) inside the iteration for loop:

Unhandled exception at 0x7524C41F in ProcYaml.exe: Microsoft C++ exception: YAML::InvalidNode at memory location 0x0040F748.

printNodeInfo(pb) shows:

  Node size: 1
  Node Tag: ?
  Node is of Type: Sequence

I am uncertain what I need to do to process this first Sequence node and get into the elements that I need: the hosts and the tasks to process for each host.

count prints out as 1 when I remove the exception throwing code (if (it->first) {...})

I guess my main misunderstanding in this is: How am I to do anything with pb if I cannot iterate over it? I am new to yaml and yaml-cpp, so I am sure there is a noob factor here.

1 Answer 1

1

When iterating over a sequence, the iterator just needs to be dereferenced:

for (YAML::const_iterator it = pb.begin(); it != pb.end(); ++it) {
  YAML::Node element = *it;
  // do something with element
}

The it->first and it->second pattern is used for iterating over maps:

for (YAML::const_iterator it = pb.begin(); it != pb.end(); ++it) {
  YAML::Node key = it->first;
  YAML::Node value = it->second;
  // do something with key, value
}

Since YAML nodes can be either scalars, sequences, or maps, you have to check the type (like you're doing) before you do any sort of iteration (unless you know exactly the structure of the input YAML).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.