MarKS
MarKS

Reputation: 504

Writing nested maps and sequences to a yaml file using YAML::Emitter

I have been trying to output a yaml file using YAML::Emitter. For instance, I need something like this to be my yaml file.

annotations:
  - run:
     type: range based
     attributes:
      start_frame:
       frame_number: 25
      end_frame:
       frame_number: 39     

So far, using my code

for (auto element : obj)
{
    basenode = YAML::LoadFile(filePath);  //loading a file throws exception when it is not a valid yaml file

    //Check if metadata is already there
    if (!basenode["file_reference"])
    {
        writeMetaData(element.getGttStream(), element.getTotalFrames(), element.getFileHash());
    }

    annotationNode["annotations"].push_back(element.getGestureName());

    annotationNode["type"] = "range based";
    output << annotationNode;

    attributesNode["attributes"]["start_frame"]["frame_number"] = element.getStartFrame();

    attributesNode["attributes"]["end_frame"]["frame_number"] = element.getEndFrame();

    output << typeNode;
    output << attributesNode;

    ofs.open(filePath, std::ios_base::app);
    ofs << std::endl << output.c_str();
}

I am getting an output like this

annotations:
  - run
type: range based
---
attributes:
 start_frame:
  frame_number: 26
 end_frame:
  frame_number: 57

I want the "type" and "attributes" under the recently pushed sequence item into the "annotations" and subsequently the same for all the following nodes.

I even tried using something like this

annotationNode[0][type] = "range based"

and the output was like this

0: type: "range based"

How do i get the recently pushed item in the sequence "annotations"?

Upvotes: 2

Views: 1436

Answers (1)

Jesse Beder
Jesse Beder

Reputation: 34054

If you're building up your root node, annotationNode, then just build it up and output it once. You wouldn't need to write either the typeNode or attributesNode to the emitter. For example, you might write

YAML::Node annotationNode;
for (auto element : obj) {
  YAML::Node annotations;
  annotations["name"] = element.getGestureName();
  annotations["type"] = ...;
  annotations["attributes"] = ...;
  annotationNode["annotations"] = annotations;
}

output << annotationNode;

Upvotes: 1

Related Questions