Reputation: 1810
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?
Upvotes: 4
Views: 4765
Reputation: 76578
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.
Upvotes: 3
Reputation: 1771
If you are looking for how to get the Python object from a yaml representation, you can use a yaml parser. Such as pyyaml.
Install with pip: pip install pyyaml
Then, for example:
>>> doc = """
product:
- sku : BL394D
quantity : 4
description : Basketball
price : 450.00
- sku : BL4438H
quantity : 1
description : Super Hoop
price : 2392.00
"""
>>> yaml.load(doc)
{
'product': [{
'description': 'Basketball',
'price': 450.0,
'quantity': 4,
'sku': 'BL394D'
}, {
'description': 'Super Hoop',
'price': 2392.0,
'quantity': 1,
'sku': 'BL4438H'
}]
}
Upvotes: 0
Reputation: 3777
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.
Upvotes: 4