Search code examples
javayamlsnakeyaml

How do I load multiple yaml files using Snake YAML Java?


I have a few yaml files in a directory. How do I load all of them into the same YAML Object (Map)?

# a.yaml
a: ValueA
c: ValueC

# b.yaml
a: ValueAA
b: ValueB

I want to a.yaml, followed by b.yaml. The result would be:

{ a: ValueAA, b: ValueB, c: ValueC }

One way I could do this is to explicitly concatenate the contents of a.yaml and b.yaml into a single String, and then load the merged String. I would like to know if I can avoid that and just load the 2 yaml files sequentially using the load() API.


Solution

  • I don't know the details of SnakeYAML, but you cannot just concatenate the two files a.yaml and b.yaml, even if they both have a mapping at the root level. Doing so you would get a duplicate key in your mapping and according to the YAML 1.2 (and 1.0) specifications you are not allowed to have duplicate keys, and the 1.1 specification states you should get a warning on a duplicate key, and the first value (you indicate you want to have the second).

    So you have to resolve this in Java, and you can do so by loading the documents from their respective files and update the data structure loaded from a.yaml with the one from b.yaml.

    You can also concatenate the files into a file with multiple documents, but for that the documents would have to be separated by a directives-end-indicator (---) or a document-end-indicator (...). You normally need to use a special "load-all" function to load such a multi-document file resulting in a list of (or iterator over) data-structures loaded from the mappings, that you then can merge.

    If you make the multi-document file programmatically, make sure to check that the files end in a newline, otherwise appending --- and the next file is not going to give the multi-document stream you expect.