Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building an array of dictionary items in YAML?

Tags:

yaml

pyyaml

Basically trying to something in yaml that could be done using this json:

{ models:  [   {      model: "a"     type: "x"     #bunch of properties...   },   {     model: "b"     type: "y"     #bunch of properties...   }  ] } 

So far this is what I have, it does not work because I am repeating my model key but what can be a proper way to do that by keeping that model key word?

models:  model:   type: "x"   #bunch of properties...  model:   type: "y"   #bunch of properties... 
like image 375
sadaf2605 Avatar asked May 13 '15 17:05

sadaf2605


People also ask

How do I create an array in YAML?

In YAML, Array represents a single key mapped to multiple values. Each value starts with a hyphen - symbol followed by space. In a single line, write the same thing above using 'square brackets syntax. '

Does YAML support arrays?

An array can contain any valid YAML value. The values in a list do not have to be the same type.

Are YAML arrays ordered?

Yes, the order of sequences is preserved. In YAML a sequence (which maps to a python list): Represents a collection indexed by sequential integers starting with zero. Example bindings to native types include Perl's array, Python's list or tuple, and Java's array or Vector.


2 Answers

Use a dash to start a new list element:

models:  - model: "a"    type: "x"    #bunch of properties...  - model: "b"    type: "y"    #bunch of properties... 
like image 50
Charles Duffy Avatar answered Oct 11 '22 18:10

Charles Duffy


You probably have been looking at YAML for too long because that what you call JSON in your post isn't, it is more a half-and-half of YAML and JSON. Lets skip the fact that JSON doesn't allow comments starting with a #, you should quote the strings that are keys and you should put , between elements in mapping:

{ "models":  [   {     "model": "a",     "type": "x"   },   {     "model": "b",     "type": "y"   }  ] } 

That is correct JSON as well as it is YAML, because YAML is a superset of JSON. You can e.g. check that online at this YAML parser.

You can convert it to the block-style you seem to prefer as YAML using ruamel.yaml.cmd (based on my enhanced version of PyYAML: pip install ruamel.yaml.cmd). You can use its commandline utility to convert JSON to block YAML (in version 0.9.1 you can also force flow style):

yaml json in.json 

which gets you:

models: - model: a   type: x - model: b   type: y 

There are some online resources that allow you to do the above, but as with any of such services, don't use them for anything important (like the list of credit-card numbers and passwords).

like image 25
Anthon Avatar answered Oct 11 '22 20:10

Anthon