Pregunta

In a YAML file, is it possible to add an item to a map after the map has already been defined?

For example, if I have a file:

fruits:
  bananas:
    quantity: 4
  apples:
    quantity: 2
  grapes:
    quantity: 37

vegetables:
  lettuce:
    quantity: 2
  beets:
    quantity: 4

and then later on realize that my "fruits" map is not complete, can I do anything later on in the file (i.e. after the "vegetables" map is defined) to append another fruit to the existing map? Something where:

fruits:
  oranges:
    quantity: 4

would be appended to the existing map instead of overwriting it?

In other words, is there a valid way to append "oranges" to the existing "fruits" map elsewhere in the file?

A bit of background: I plan on using yaml-cpp with C++. I am using YAML as an input file format for a program I am writing. I will parse the file that a user creates and translate the structure into the objects in my program. I would like to be able to append items to a map because it is common for objects (in this example "fruits") to be scattered in an input file as a user realizes they are needed or used near other objects that reference them.

¿Fue útil?

Solución

It isn't valid YAML to have a repeated key. E.g., the following is not valid YAML:

fruits: foo
fruits: bar

If your YAML file starts with:

fruits: whatever
bar: baz

then there is no way to modify the value associated with the key fruits by appending to the file. Different YAML parsers may interpret repeated keys in their own way, but the spec defines it as an error.

You could post-process a YAML file, if you want, e.g.:

fruits1: whatever
bar: baz
fruits2: something else

and then in your code, just merge them values associated with fruits1 and fruits2 (and fruits3, ...) however you like.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top