3

I.e. is there a way to transform this example:

myhash:
  - name: name1
    value: value1
myhash:
  - name: name2
    value: value2

into:

myhash:
  - name: name1
    value: value1
  - name: name2
    value: value2

As soon as I noticed by default YAML transforms it into:

myhash:
  - name: name2
    value: value2
Anthon
  • 69,918
  • 32
  • 186
  • 246
kay
  • 693
  • 2
  • 7
  • 13
  • **Note:** Not sure why @Anthon did not mention this, but this can also be handled with anchors and aliases: see also https://stackoverflow.com/questions/9254178/is-there-yaml-syntax-for-sharing-part-of-a-list-or-map – dreftymac May 30 '17 at 23:48
  • **See also:** https://stackoverflow.com/questions/24090177/how-to-merge-yaml-arrays/30770740#30770740 – dreftymac May 30 '17 at 23:49
  • Both questions that you linked to, have valid YAML to start with, so that makes them inapplicable to the OPs primary problem. AFAIK no amount of inserting anchors and/or aliases will make invalid YAML into valid YAML, but I will be glad to be proved wrong (e.g. if there is a non-standard parser that I have not worked with that will support this). If your observations are valid, please provide an answer here. If you can't you should probably remove your comments. – Anthon May 31 '17 at 05:51
  • @Anthon Greetings Anthon. Just to be clear, nothing here or above states that your answer is incorrect. If we assume that the user *insists* to use "non-valid" YAML, then your answer is indeed correct and complete, and nothing else needs to be stated. However, some SO readers may mistakenly believe that there is no way to correct the primary problem here, and assume *"there is no YAML spec which could do what I want"*. Assuming the reader does not *insist* to use non-unique keys, then there are other alternatives. These other alternatives merited express inclusion, hence those links. Thanks. – dreftymac Oct 30 '17 at 21:05

1 Answers1

5

In the YAML 1.2 specification it is stated that "mapping - an unordered association of unique keys to values" (emphasis mine). Your keys are not unique and what happens because of that depends on the library implementation (throw an error, ignore one of the keys).

What your parser obviously does is throw away the first key/value pair. What you want to do cannot be done by loading the first example using a YAML parser. You can of course write a utility that splits up the text that is not using the YAML parser.

Please note that in YAML 1.1:

It is an error for two equal keys to appear in the same mapping node. In such a case the YAML processor may continue, ignoring the second key: value pair and issuing an appropriate warning.

This is e.g. not how the YAML 1.1 parser PyYAML works: it doesn't ignore the value for the second (or following) key, nor does it issue a warning.

Anthon
  • 69,918
  • 32
  • 186
  • 246