Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

YAML: how to interpret sequence of mappings

Tags:

python

yaml

On page 8 of the YAML spec, the authors provide an example of page 4's "sequence of mappings" like this:

product:
    - sku         : BL394D
      quantity    : 4
      description : Basketball
      price       : 450.00
    - sku         : BL4438H
      quantity    : 1
      description : Super Hoop
      price       : 2392.00

For my own understanding how would I (roughly) represent that in, say, Python?

Mapping > Sequence > Mapping, Mapping, Mapping ... ?

{"Product" : ({ "sku" : "BL394D" }, {"quantity" : 4 }), ... }

Or Mapping > Sequence of mapping 1, 2, 3, ... ?

{"Product" : ({ "sku" : "BL394D" }), ({ "quantity" : 4 }), ... )}

Or something else?

like image 719
mellow-yellow Avatar asked Sep 07 '25 12:09

mellow-yellow


2 Answers

It would appear as so in JSON:

{
    "product": [
        {
            "sku": "BL394D",
            "quantity": 4,
            "description": "Basketball",
            "price": 450
        },
        {
            "sku": "BL4438H",
            "quantity": 1,
            "description": "Super Hoop",
            "price": 2392
        }
    ]
}

So in Python, it would be an object that has a map to product, which is an array of other objects with the properties sku, quantity, etc.

like image 147
azizj Avatar answered Sep 10 '25 05:09

azizj


At the root of the YAML document there is a mapping. This has one key product. Its value is a sequence, with two items (indicated by the dashes -).

The sequence elements are again mappings, and the first key/value pair of each of these mappings starts on the same line as the sequence element (its key is sku).

In Python, by default, a mapping is loaded as a dict and a sequence is loaded as a list, so you could define the data in Python using:

dict(product=[dict(
  sku='BL394D', quantity= 4, description='Basketball', price=450.00),
  dict(sku='BL4438H', quantity= 1, description='Super Hoop', price=2392.00),
])

You can of course just load the data structure and then print that to see how this is loaded.

like image 39
Anthon Avatar answered Sep 10 '25 03:09

Anthon