Reputation: 29477
I am trying to design the configuration file format for my app and have chosen YAML. However, this (obviously) means I need to be able to define, parse and validate proper YAML syntax!
In the config file, there must be a collection/sequence called widgets
. This sequence needs to contain a set of typed widgets (possible types are fizz
, buzz
and foobaz
). Each widget also has a name
and various other properties (depending on the type). For example:
myappconfig.yaml
================
widgets:
- buzz:
name: Red Buzz
isSilly: true
- buzz:
name: Blue Buzz
isSilly: false
- foobaz:
name: Abracadabra
rating: 3000
specialty: Such YAML much amaze
My simple question is: Have I created a proper/valid YAML file above? Meaning, based on my constraints, am I understanding YAML syntax correctly in my implementation?
Upvotes: 4
Views: 2338
Reputation: 21
Unfortunately, not all text editors and IDEs validate YAML.
Difff.app validates, formats, and converts YAML or other text files. There is an article about YAML basics with examples.
Upvotes: 0
Reputation: 1383
If the widget name should be unique, you can use it for keys:
widgets:
RedBuzz:
type: buzz
isSilly: true
BlueBuzz:
type: buzz
isSilly: false
Abracadabra:
type: foobaz
rating: 3000
specialty: Such YAML much amaze
This one uses grouping by widget type:
widgets:
buzz:
- RedBuzz:
isSilly: true
- Blue Buzz:
isSilly: false
foobaz:
- Abracadabra:
rating: 3000
specialty: Such YAML much amaze
Also if you're feeling nerdy you can use widgets types merge like this:
buzz_widget: &buzz_widget
type: buzz
foobaz_widget: &foobaz_widget
type: foobaz
widgets:
RedBuzz:
isSilly: true
<<: *buzz_widget
BlueBuzz:
isSilly: false
<<: *buzz_widget
Abracadabra:
rating: 3000
specialty: Such YAML much amaze
<<: *foobaz_widget
As for me, using nested key-values structure (for non-primitive elements) is preferable. Being parsed into a map, you can always access it's values as a collection. At the same time you have unique constraint and constant access time (by key). If your keys should not be unique, then you should try restructuring it before giving back to sequence.
Upvotes: 1
Reputation: 1373
You can check the syntax of your YAML, e.g. on this website.
Your YAML is parsed as this:
{'widgets': [{'buzz': {'name': 'Red Buzz', 'isSilly': True}}, {'buzz': {'name': 'Blue Buzz', 'isSilly': False}}, {'foobaz': {'rating': 3000, 'name': 'Abracadabra', 'specialty': 'Such YAML much amaze'}}]}
which looks like what you seem to be after.
Upvotes: 4