Ben G
Ben G

Reputation: 26761

Extend an array in YAML?

Suppose I have:

base_array:
  -1
  -2

how could I do something like:

my_array: << base_array
  -3

so that my_array was [1,2,3]

Update: I should specify that I want the extending to occur inside the YAML itself.

Upvotes: 64

Views: 28482

Answers (2)

raviabhiram
raviabhiram

Reputation: 720

I needed to do the same thing but to run on Azure DevOps Pipeline. In particular, I had to update the stage dependency dynamically. How I did it:

dependents: [Stage_A, Stage_B]
otherDependents: [Stage_C] # This needed to be added by policy to the pipeline's execution
dependsOn:
- ${{ each dependent in dependents }}:
  - ${{ dependent }}
- ${{ each dependent in otherDependents }}:
  - ${{ dependent }}

Doing so resulted in the required setup:

dependents: [Stage_A, Stage_B]
otherDependents: [Stage_C] # This needed to be added by policy to the pipeline's execution
dependsOn:
  - Stage_A
  - Stage_B
  - Stage_C

I say dynamically because the variable dependents came from a template to which I had to append Stage_C.

Upvotes: 3

hc_dev
hc_dev

Reputation: 9377

Since the already commented issue#35 exists, merge-keys << doesn't help you. It only merges/inserts referenced keys into a map (see YAML docs merge). Instead you should work with sequences and use anchor & and alias *.

So your example should look like this:

base_list: &base
    - 1
    - 2

extended: &ext
    - 3

extended_list:
    [*base, *ext]

Will give result in output like this (JSON):

{
  "base_list": [
    1, 
    2
  ], 
  "extended": [
    3
  ], 
  "extended_list": [
    [
      1, 
      2
    ], 
    [
      3
    ]
  ]
} 

Although not exactly what you expected, but maybe your parsing/loading environment can flatten the nested array/list to a simple array/list.

You can always test YAML online, for example use:

Upvotes: 13

Related Questions