34
votes

How can I create nested lists in YAML? I want to get:

 {"Hello": ["as", ["http://", ["cat"]]]}

Here's my YAML that doesn't work (with pyYaml):

  Hello:
    - "as"
      - "http://"
        - cat

What am I doing wrong?

Specifically, I'm trying to generate the following JSON from YAML:

"URL" : {
  "Description" : "URL of the website",
  "Value" :  { "Fn::Join" : [ "", [ "http://", { "Fn::GetAtt" : [ "ElasticLoadBalancer", "DNSName" ]}]]}
}

Here's the closest YAML I've got working, but it doesn't give quite what I need.

YAML is:

  Outputs:
    URL:
      Description: URL of the website
      Value:
        "Fn::Join":
        - ""
        - "http://"
        - "Fn::GetAtt":
          - ElasticLoadBalancer
          - DNSName

This results in:

    "URL": {
        "Description": "URL of the website", 
        "Value": {
            "Fn::Join": [
                "", 
                "http://", 
                {
                    "Fn::GetAtt": [
                        "ElasticLoadBalancer", 
                        "DNSName"
                    ]
                }
            ]
        }
    }

This is almost correct, but after "" there should be a nested list, not just another list item. How can I fix this?

This is going to be fed into an API, so the output must match completely.

3

3 Answers

33
votes

And the answer is:

URL:
  Description: URL of the website
  Value:
    "Fn::Join":
      - ""
      - - "http://"
        - "Fn::GetAtt":
            - ElasticLoadBalancer
            - DNSName

(see http://pyyaml.org/wiki/PyYAMLDocumentation#YAMLsyntax - "block sequences can be nested")

7
votes

Start a nested list from a new line. Using this approach it is easy to figure out.

Read this and this article. They have a lot of examples.

Try like this:

YAML

Value:
    "Fn::Join":
      - ""
      -
         - "http://"
         - "Fn::GetAtt":
              - ElasticLoadBalancer
              - DNSName

Equivalent JSON:

{
  "URL": {
    "Description": "URL of the website",
    "Value": {
      "Fn::Join": [
        "",
        [
          "http://",
          {
            "Fn::GetAtt": [
              "ElasticLoadBalancer",
              "DNSName"
            ]
          }
        ]
      ]
    }
  }
}
4
votes

Try:

Hello: 
  ["as", 
    ["http://", 
      [cat]
    ]
]

Json output:

{
  "Hello": [
    "as", 
    [
      "http://", 
      [
        "cat"
      ]
    ]
  ]
}