Allen Yuan
Allen Yuan

Reputation: 97

How to save [x, y] in yaml file

In .yaml file. I know how to save x, y in

world:     

   radius: 20
        x: -70
        y: -30

My question is can I save it in the below format

world:

        radius: 20
        [-30, -70]

Basically, I want to store two float number (x, y) in one line.

I program in c++

Upvotes: 0

Views: 974

Answers (2)

Anthon
Anthon

Reputation: 76692

No you can not, not in the way that you describe. You can easily test that by pasting your required output in an online YAML parser (e.g. this one) or, if you have Python installed, by installing a virtualenv and do¹:

pip install ruamel.yaml.cmd
yaml round-trip input.yaml

Your required output has, at the top-level, a mapping with key world, for which the value starts out with being a mapping (with key radius and value 20) then switches to a flow style sequence: [-30, -70]. That is incorrect, you cannot mix mapping key-value pairs with sequences.

There are several ways to correct this. You can do:

world:
  radius: 20
  [-30, -70]:

which is perfectly fine YAML, the pair -30, -70 being a key for a value null which doesn't need to be made explicit. Please note that some YAML parsers do not support this form, the one I linked to does.

The, IMO, most logical one-line solution:

world:
  radius: 20
  [x, y]: [-30, -70]

which you can get by compiling and running:

#include <iostream>
#include "yaml-cpp/yaml.h"

int main()
{
   YAML::Emitter out;
   out << YAML::BeginMap;
   out << YAML::Key << "world";
   out << YAML::Value << YAML::BeginMap;
   out << YAML::Key << "radius";
   out << YAML::Value << 20;
   out << YAML::Key << YAML::Flow << YAML::BeginSeq << "x" << "y" << YAML::EndSeq;
   out << YAML::Key << YAML::Flow << YAML::BeginSeq << "-30" << "-70" << YAML::EndSeq;

   std::cout << out.c_str() << "\n";
   return 0;
}

Your first YAML example is invalid YAML as well: you should align the keys and not the colons in a mapping:

world:     

   radius: 20
   x: -70
   y: -30

¹ Disclaimer: I am the author of the ruamel.yaml.cmd package. Using a local test can be important if your YAML file contains sensitive data.

Upvotes: 1

Jesse Beder
Jesse Beder

Reputation: 34054

When emitting a sequence, you can preface it with YAML::Flow. From the documentation:

YAML::Emitter out;
out << YAML::Flow;
out << YAML::BeginSeq << 2 << 3 << 5 << 7 << 11 << YAML::EndSeq;

produces

[2, 3, 5, 7, 11]

Upvotes: 1

Related Questions