Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

YAML multi-line strings: keys vs array values

This is very specific but left me stumped. We treat nested keys + regular arrays almost the same on parsing – sometimes adding extra info when needed, like this:

---
Entry 1:
    - lorem:
        true
    - ipsum
    - dolor
Entry 2:
    - lorem
    - ipsum:
        true
    - dolor
...

… which gives me this JSON:

{
  "Entry 2": [
    "lorem", 
    {
      "ipsum": true
    }, 
    "dolor"
  ], 
  "Entry 1": [
    {
      "lorem": true
    }, 
    "ipsum", 
    "dolor"
  ]
}

All cool and fine. Entering multiline strings for content it gets messier but still works ok like this (keep pasting those to Online YAML Parser or some other compiler for reference):

---
#works:

Test:
  - lorem
  - ipsum
  - dolor
? |-
    multiline
    Test
:
  - lorem
  - ipsum:
      true
  - dolor
...

going deeper, multiline strings in my 2nd level array work as well, as expected by the spec:

---
#works:
Test:
    - |-
        multiline
        lorem
    - ipsum
    - dolor
? |-
    multiline
    Test
:
    - lorem
    - ipsum:
        true
    - dolor
...

Wohoo! But as soon as I mix multi-line keys and multi-line array strings on the same level, my setup breaks:

---
#breaks:
Test:
    - |-
        multiline
        lorem
    ? |- 
        multiline
        ipsum
    : 
        true
? |-
    multiline
    Test
:
    - lorem
    - ipsum:
        true
    - dolor
...

How to fix that?

like image 600
Paracetamol Avatar asked Jun 20 '16 17:06

Paracetamol


1 Answers

YAML breaks if you mix keys and array items on the same level. You do not need multi-line strings for that:

- 1
? 2
: 3

What should this parse to? An array? A mapping? This, however, works:

- 1
- ? 2
  : 3

So you can fix your YAML like this:

---
Test:
    - |-
        multiline
        lorem
    - ? |- 
          multiline
          ipsum
      : 
        true
? |-
    multiline
    Test
:
    - lorem
    - ipsum:
        true
    - dolor
...
like image 89
flyx Avatar answered Nov 13 '22 20:11

flyx