MA Prado
MA Prado

Reputation: 21

YAML Merge single sequence and deserialize with SnakeYAML JAVA

I'm trying to merge sequence values with YAML to after deserialize with SnakeYAML with JAVA.

I expected this results:

{
  "root": {
    "seq4": [
      "001", 
      "002",
      "003"
    ], 
    "seq3": [
      "001", 
      "002",
      "003"
    ], 
    "seq2": [
      "001", 
      "002"
    ], 
    "seq1": [
      "001", 
      "002"
    ]
  }
}

But this is not possible for me with this YAML example:

root: 
  seq1: &seq1
    - '001' #first
    - '002' #secod
  seq2: *seq1
  seq3: &seq3
    *seq1
    - '003' #third
  seq4: *seq3

This example return the message:

while parsing a block mapping in "", line 2, column 3: seq1: &anch1 ^ expected , but found '' in "", line 7, column 5: *anch1 ^

example

Also, I probe this YAML definition but its return error to:

root: 
  seq1: &anch1
    - '001' #first
    - '002' #secod
  seq2: *anch1
  seq3: &anch2
    <<: *anch1
    - '003' #third
  seq4: *anch2

Any idea?? Thanks

Upvotes: 0

Views: 924

Answers (2)

Anthon
Anthon

Reputation: 76599

In YAML there is no language independent sequence element like there is language independent merge key for mappings.

One of the reasons for that is that you could still use the merge key (<<) without special meaning if the value is not a mapping.

You can of course do something like:

root: 
  seq1: &seq1
    - '001' #first
    - '002' #secod
  seq2: *seq1
  seq3: !CombineSequences &seq3
    - *seq1
    - ['003'] #third
  seq4: *seq3

And have a special type CombineSequences that combines its elements into one large list/array.

Upvotes: 1

SBylemans
SBylemans

Reputation: 1764

Found this: Github issue. So your scenario would not be possible...

Also look at this question regarding merging of YAML arrays: How to merge YAML arrays

A workaround is to assign unique keys to the values, like so:

root: 
  seq1: &anch1
    1: '001' #first
    2: '002' #secod
  seq2: *anch1
  seq3: &anch2
    <<: *anch1
    3: '003' #third
  seq4: *anch2

This will yield:

"root": {
  "seq3": {
    "1": "001", 
    "2": "002", 
    "3": "003"
  }, 
  "seq2": {
    "1": "001", 
    "2": "002"
  }, 
  "seq1": {
    "1": "001", 
    "2": "002"
  }, 
  "seq4": {
    "1": "001", 
    "2": "002", 
    "3": "003"
  }
}

Upvotes: 1

Related Questions