yamlmapping

Can I merge nested mappings in yaml?


Given the following example:

.a: &a
    sheep: "a"
.b : &b
    cow: "a"

edileMamals: &edible_mamals
  << : *a
  << : *b

edibleAnimals: &edible_animals
    mamals:
        << : *edible_mamals
    fish:
        salmon: "a"
        tuna: "a"

I would like now to create allAnimals that relies on edibleAnimals and extends both mamals and fish. My naive approach of doing it like this:

allAnimals:
    << : *edible_animals
    mamals:
        horse: "a"
    fish:
        dolphin: "a"

got me:

allAnimals:
    mamals:
        horse: "a"
    fish:
        dolphin: "a"

instead of:

allAnimals:
    mamals:
        sheep: "a"
        cow: "a"
        horse: "a"
    fish:
        salmon: "a"
        tuna: "a"
        dolphin: "a"

I understand that the merge function sees that both edibleAnimals and allAnimals have the mamals key, so it takes the later. But is there a way to perform a multilayer merge?

So far I only found an answer here that suggest to add extra code to support the "+" suffix operator as a workaround , but I'm looking for a generic/native solution.


Solution

  • After looking through the documentation of yaml I can say that at least by April 2025 "deep merge" or "nested merge" doesn't exist in yaml.