The yaml format
Содержание:
- YAML Tutorial Quick Start: A Simple File
- Validators
- The «yaml_validator» task
- Usage
- Типы файлов YAML
- Release History
- Устранение неполадок при открытии файлов YAML
- Release History
- The «yaml_validator» task
- Outline Indentation and Whitespace
- Usage
- Getting Started
- Indentation of block sequences¶
- The «yaml_validator» task
- Синтаксис YAML¶
YAML Tutorial Quick Start: A Simple File
Let’s take a look at a YAML file for a brief overview.
--- doe: "a deer, a female deer" ray: "a drop of golden sun" pi: 3.14159 xmas: true french-hens: 3 calling-birds: - huey - dewey - louie - fred xmas-fifth-day: calling-birds: four french-hens: 3 golden-rings: 5 partridges: count: 1 location: "a pear tree" turtle-doves: two
The file starts with three dashes. These dashes indicate the start of a new YAML document. YAML supports multiple documents, and compliant parsers will recognize each set of dashes as the beginning of a new one.
Next, we see the construct that makes up most of a typical YAML document: a key-value pair. Doe is a key that points to a string value: a deer, a female deer.
YAML supports more than just string values. The file starts with six key-value pairs. They have four different data types. Doe and ray are strings. Pi is a floating-point number. Xmas is a boolean. French-hens is an integer. You can enclose strings in single or double-quotes or no quotes at all. YAML recognizes unquoted numerals as integers or floating point.
The seventh item is an array. Calling-birds has four elements, each denoted by an opening dash.
I indented the elements in calling-birds with two spaces. Indentation is how YAML denotes nesting. The number of spaces can vary from file to file, but tabs are not allowed. We’ll look at how indentation works below.
Finally, we see xmas-fifth-day, which has five more elements inside it, each of them indented. We can view xmas-fifth-day as a dictionary that contains two string, two integers, and another dictionary. YAML supports nesting of key-values, and mixing types.
Before we take a deeper dive, let’s look at how this document looks in JSON. I’ll throw it in this handy JSON to YAML converter.
{ "doe": "a deer, a female deer", "ray": "a drop of golden sun", "pi": 3.14159, "xmas": true, "french-hens": 3, "calling-birds": , "xmas-fifth-day": { "calling-birds": "four", "french-hens": 3, "golden-rings": 5, "partridges": { "count": 1, "location": "a pear tree" }, "turtle-doves": "two" } }
JSON and YAML have similar capabilities, and you can convert most documents between the formats.
Validators
Here are all the validators Yamale knows about. Every validator takes a keyword telling
Yamale whether or not that node must exist. By default every node is required. Example:
You can also require that an optional value is not by using the keyword. By default
Yamale will accept as a valid value for a key that’s not required. Reject values
with in any validator. Example: .
Some validators take keywords and some take arguments, some take both. For instance the
validator takes one or more constants as arguments and the keyword:
String —
Validates strings.
- keywords
- : len(string) >= min
- : len(string) <= max
- : Rejects strings that contains any character in the excluded value.
Examples:
str(max=10, exclude=’?!’): Allows only strings less than 11 characters that don’t contain ? or !.
Regex —
Validates strings against one or more regular expressions.
- arguments: one or more Python regular expression patterns
- keywords:
- : A friendly description for the patterns.
- : Validates strings in a case-insensitive manner.
-
: in a pattern matches newline characters in a validated string in addition to
matching every character that isn’t a newline.
Examples:
- : Allows only strings less than 11 characters that don’t contain or .
-
: Allows only strings that contain two or
more identical digit sequences, each separated by a whitespace character. Non-matching strings
like are rejected with a message like -
: Allows the string as well
as multiline strings that contain the line .
Validates integers.
- keywords
- : int >= min
- : int <= max
Validates integers and floats.
- keywords
- : num >= min
- : num <= max
Enum —
Validates from a list of constants.
arguments: constants to test equality with
Examples:
enum(‘a string’, 1, False): a value can be either ‘a string’, 1 or False
Day —
Validates a date in the form of YYYY-MM-DD.
- keywords
- : date >= min
- : date <= max
Examples:
day(min=’2001-01-01′, max=’2100-01-01′): Only allows dates between 2001-01-01 and 2100-01-01.
Timestamp —
Validates a timestamp in the form of YYYY-MM-DD HH:MM:SS.
- keywords
- : time >= min
- : time <= max
Examples:
timestamp(min=’2001-01-01 01:00:00′, max=’2100-01-01 23:00:00′): Only allows times between
2001-01-01 01:00:00 and 2100-01-01 23:00:00.
List —
Validates lists. If one or more validators are passed to only nodes that pass at
least one of those validators will be accepted.
- arguments: one or more validators to test values with
- keywords
- : len(list) >= min
- : len(list) <= max
Examples:
- : Validates any list
-
: Only validates lists that contain the include
or integers and contains a minimum of 4 items.
Map —
Validates maps. Use when you want a node to contain freeform data. Similar to , takes
one or more validators to run against the values of its nodes, and only nodes that pass at least
one of those validators will be accepted. By default, only the values of nodes are validated and
the keys aren’t checked.
- arguments: one or more validators to test values with
- keywords
Examples:
- : Validates any map
- : Only validates maps whose values are strings or integers.
- : Only validates maps whose keys are integers and values are strings. would be valid but would not.
IP Address —
Validates IPv4 and IPv6 addresses.
- keywords
Examples:
- : Allows any valid IPv4 or IPv6 address
- : Allows any valid IPv4 address
- : Allows any valid IPv6 address
Validates MAC addresses.
Examples:
mac(): Allows any valid MAC address
Any —
Validates against a union of types. Use when a node must contain one and only one of several types. It is valid
if at least one of the listed validators is valid. If no validators are given, accept any value.
arguments: validators to test values with (if none is given, allow any value; if one or more are given,
one must be present)
Examples:
- : Validates either an integer or a null value.
- : Validates either a number or an included ‘vector’ type.
- : validates to a string that is exactly 3, 5, or 7 characters long
- : Allows any value.
Include —
Validates included structures. Must supply the name of a valid include.
arguments: single name of a defined include, surrounded by quotes.
Examples:
include(‘person’)
Custom validators
It is also possible to add your own custom validators. This is an advanced topic, but here is an
example of adding a validator and using it in a schema as
import yamale import datetime from yamale.validators import DefaultValidators, Validator class Date(Validator): """ Custom Date validator """ tag = 'date' def _is_valid(self, value): return isinstance(value, datetime.date) validators = DefaultValidators.copy() # This is a dictionary validators = Date schema = yamale.make_schema('./schema.yaml', validators=validators) # Then use `schema` as normal
The «yaml_validator» task
In your project’s Gruntfile, add a section named to the data object passed
into .
grunt.initConfig({ yaml_validator{ options{}, your_target{ options{} src},},});
All options are by default which disables their use.
Type:
Default value:
In case the value is not , the given string will be used as log file where all the
task output is written.
Type:
Default value:
The most complex style of checking validity.
Type:
Default value:
Please note that the callback is being used by this plugin and any method written for it,
will be run after the one implemented in this plugin.
The callback get called with two parameters, of which the first is the error in question,
while the second is the file path of the given Yaml file.
Type:
Default:
Write the given Yaml file as pretty printed JSON in the same path, just by changing the file extension to .
Please note that any existing JSON files will be cruelly overwritten.
By using the default option values, only the validity of the configured Yaml files are checked.
grunt.initConfig({ yaml_validator{ defaults{ src'configuration/*.yml','other/important/*_stuff.yml'}}});
All output is written in the log file as well as to the standard output.
grunt.initConfig({ yaml_validator{ logged{ options{ log'yaml-validator.log'}, src'configuration/*.yml','other/important/*_stuff.yml'}}});
In case an array is found, all its members are assumed to have the given structure.
This can be seen in the property, which according to the configuration below,
should be an array, for which all items are objects, which all should have a and
properties, with the given types.
The array is made of strings, thus all items in that array must be a string.
grunt.initConfig({ yaml_validator{ custom{ options{ structure{ school{ description'string', code'number', principal{ name'string'}, classRooms{ name'string', id'number'}, teachers'string'}}}, src'configuration/*.yml','other/important/*_stuff.yml'}}});
Using the callback, the possible parsing errors can be retrieved.
grunt.initConfig({ yaml_validator{ custom{ options{ yaml{onWarningfunction(error,filepath){console.log(filepath +' has error: '+ error);}}}, src'configuration/*.yml','other/important/*_stuff.yml'}}});
It is possible to use the to have all the files processed,
to be saved in JSON format, in the same file path as the original Yaml files.
grunt.initConfig({ yaml_validator{ custom{ options{ writeJsontrue}, src'configuration/*.yml','other/important/*_stuff.yml'}}});
Usage
Command line
Yamale can be run from the command line to validate one or many YAML files. Yamale will search the
directory you supply (current directory is default) for YAML files. Each YAML file it finds it will
look in the same directory as that file for its schema, if there is no schema Yamale will keep
looking up the directory tree until it finds one. If Yamale can not find a schema it will tell you.
Usage:
usage: yamale Validate yaml files. positional arguments: PATH folder to validate. Default is current directory. optional arguments: -h, --help show this help message and exit -s SCHEMA, --schema SCHEMA filename of schema. Default is schema.yaml. -n CPU_NUM, --cpu-num CPU_NUM number of CPUs to use. Default is 4. -p PARSER, --parser PARSER YAML library to load files. Choices are "ruamel" or "pyyaml" (default). --no-strict Disable strict mode, unexpected elements in the data will be accepted.
API
There are several ways to feed Yamale schema and data files. The simplest way is to let Yamale take
care of reading and parsing your YAML files.
All you need to do is supply the files’ path:
# Import Yamale and make a schema object: import yamale schema = yamale.make_schema('./schema.yaml') # Create a Data object data = yamale.make_data('./data.yaml') # Validate data against the schema. Throws a ValueError if data is invalid. yamale.validate(schema, data)
You can pass a string of YAML to and instead of passing a file path
by using the parameter:
data = yamale.make_data(content=""" name: Bill age: 26 height: 6.2 awesome: True """)
If is valid, nothing will happen. However, if is invalid Yamale will throw a
with a message containing all the invalid nodes:
try: yamale.validate(schema, data) print('Validation success! ') except ValueError as e: print('Validation failed!\n%s' % str(e)) exit(1)
and an array of .
try: yamale.validate(schema, data) print('Validation success! ') except YamaleError as e: print('Validation failed!\n') for resul in e.value.results: print("Error validating data '%s' with '%s'\n\t" % (result.data, result.schema)) for error in result.errors: print('\t%s' % error) exit(1)
You can also specifiy an optional if you’d like to use the (YAML 1.2 support) instead:
# Import Yamale and make a schema object, make sure ruamel.yaml is installed already. import yamale schema = yamale.make_schema('./schema.yaml', parser='ruamel') # Create a Data object data = yamale.make_data('./data.yaml', parser='ruamel') # Validate data against the schema same as before. yamale.validate(schema, data)
Schema
To use Yamale you must make a schema. A schema is a valid YAML file with one or more documents
inside. Each node terminates in a string which contains valid Yamale syntax. For example,
represents a .
A basic schema:
name: str() age: int(max=200) height: num() awesome: bool()
And some YAML that validates:
name: Bill age: 26 height: 6.2 awesome: True
Take a look at the section for more complex schema ideas.
Includes
Schema files may contain more than one YAML document (nodes separated by ). The first document
found will be the base schema. Any additional documents will be treated as Includes. Includes allow
you to define a valid structure once and use it several times. They also allow you to do recursion.
A schema with an Include validator:
person1: include('person') person2: include('person') --- person: name: str() age: int()
Some valid YAML:
person1: name: Bill age: 70 person2: name: Jill age: 20
Every root node not in the first YAML document will be treated like an include:
person: include('friend') group: include('family') --- friend: name: str() family: name: str()
Is equivalent to:
person: include('friend') group: include('family') --- friend: name: str() --- family: name: str()
Recursion
You can get recursion using the Include validator.
This schema:
person: include('human') --- human: name: str() age: int() friend: include('human', required=False)
Will validate this data:
person: name: Bill age: 50 friend: name: Jill age: 20 friend: name: Will age: 10
Adding external includes
After you construct a schema you can add extra, external include definitions by calling
. This method takes a dictionary and adds each key as another include.
Strict mode
By default Yamale will provide errors for extra elements present in lists and maps that are not
covered by the schema. With strict mode disabled (using the command line option),
additional elements will not cause any errors. In the API, strict mode can be toggled by passing
the strict=True/False flag to the validate function.
It is possible to mix strict and non-strict mode by setting the strict=True/False flag in the
include validator, setting the option only for the included validators.
Типы файлов YAML
Ассоциация основного файла YAML
.YAML
Формат файла: | .yaml |
Тип файла: | YAML Document |
Файл, созданный в YAML (YAML Не Markup Language) формат. Формат используется для сериализации данных. Формат читаемый человеком и может быть включена в несколько различных языков программирования, которые поддерживают YAML библиотек.
Создатель: | Unknown Developer |
Категория файла: | Файлы разработчика |
Ключ реестра: | HKEY_CLASSES_ROOT\.yaml |
Программные обеспечения, открывающие YAML Document:
Microsoft Notepad, разработчик — Microsoft Corporation
Совместимый с:
Windows |
Mac |
Linux |
Notepad++, разработчик — Don Ho
Совместимый с:
Windows |
Mac |
Linux |
MacroMates TextMate, разработчик — MacroMates
Совместимый с:
Mac |
Vim, разработчик — Bram Moolenaar
Совместимый с:
Windows |
Mac |
Linux |
Unix |
OS X El Capitan |
Release History
-
(2020-05-29)
- Minimum Node.js version lifted from to
- Updated to
-
(2019-01-22)
- Minimum Node.js version lifted from to
- Updated to
-
(2016-08-10)
- Dependencies are sure up to date, among version
- Grunt is now the minimum
- Use shared ESLint configuration and ESLint directly without the Grunt.js plugin
- (2016-02-22)
-
(2016-02-22)
- Minimum Node.js version required/supported is now (LTS)
- Update dependencies
- (2014-12-17)
- (2014-11-03)
- (2014-11-03)
- (2014-11-03)
- (2014-11-03)
- (2014-11-03)
- (2014-11-03)
- (2014-10-31)
- (2014-10-30)
- (2014-10-29)
- (2014-10-28)
- (2014-10-27)
- (2014-10-27)
- (2014-10-27)
- (2014-10-27)
Устранение неполадок при открытии файлов YAML
Общие проблемы с открытием файлов YAML
Microsoft Notepad не установлен
Дважды щелкнув по файлу YAML вы можете увидеть системное диалоговое окно, в котором сообщается «Не удается открыть этот тип файла». В этом случае обычно это связано с тем, что на вашем компьютере не установлено Microsoft Notepad для %%os%%. Так как ваша операционная система не знает, что делать с этим файлом, вы не сможете открыть его дважды щелкнув на него.
Совет: Если вам извстна другая программа, которая может открыть файл YAML, вы можете попробовать открыть данный файл, выбрав это приложение из списка возможных программ.
Установлена неправильная версия Microsoft Notepad
В некоторых случаях у вас может быть более новая (или более старая) версия файла YAML Document, не поддерживаемая установленной версией приложения. При отсутствии правильной версии ПО Microsoft Notepad (или любой из других программ, перечисленных выше), может потребоваться загрузить другую версию ПО или одного из других прикладных программных средств, перечисленных выше. Такая проблема чаще всего возникает при работе в более старой версии прикладного программного средства с файлом, созданным в более новой версии, который старая версия не может распознать.
Совет: Иногда вы можете получить общее представление о версии файла YAML, щелкнув правой кнопкой мыши на файл, а затем выбрав «Свойства» (Windows) или «Получить информацию» (Mac OSX).
Резюме: В любом случае, большинство проблем, возникающих во время открытия файлов YAML, связаны с отсутствием на вашем компьютере установленного правильного прикладного программного средства.
Даже если на вашем компьютере уже установлено Microsoft Notepad или другое программное обеспечение, связанное с YAML, вы все равно можете столкнуться с проблемами во время открытия файлов YAML Document. Если проблемы открытия файлов YAML до сих пор не устранены, возможно, причина кроется в других проблемах, не позволяющих открыть эти файлы. Такие проблемы включают (представлены в порядке от наиболее до наименее распространенных):
Release History
-
(2020-05-29)
- Minimum Node.js version lifted from to
- Updated to
-
(2019-01-22)
- Minimum Node.js version lifted from to
- Updated to
-
(2016-08-10)
- Dependencies are sure up to date, among version
- Grunt is now the minimum
- Use shared ESLint configuration and ESLint directly without the Grunt.js plugin
- (2016-02-22)
-
(2016-02-22)
- Minimum Node.js version required/supported is now (LTS)
- Update dependencies
- (2014-12-17)
- (2014-11-03)
- (2014-11-03)
- (2014-11-03)
- (2014-11-03)
- (2014-11-03)
- (2014-11-03)
- (2014-10-31)
- (2014-10-30)
- (2014-10-29)
- (2014-10-28)
- (2014-10-27)
- (2014-10-27)
- (2014-10-27)
- (2014-10-27)
The «yaml_validator» task
Overview
In your project’s Gruntfile, add a section named to the data object passed
into .
grunt.initConfig({ yaml_validator: { options: { // Task-specific options go here. }, your_target: { options: { // Multi task specific options go here. } // Target-specific file lists and/or options go here. src: }, }, });
Options
All options are by default which disables their use.
options.log
Type:
Default value:
In case the value is not , the given string will be used as log file where all the
task output is written.
Type:
Default value:
The most complex style of checking validity.
options.yaml
Type:
Default value:
Options passed to .
Please note that the callback is being used by this plugin and any method written for it,
will be run after the one implemented in this plugin.
The callback get called with two parameters, of which the first is the error in question,
while the second is the file path of the given Yaml file.
options.writeJson
Type:
Default:
Write the given Yaml file as pretty printed JSON in the same path, just by changing the file extension to .
Please note that any existing JSON files will be cruelly overwritten.
Usage Examples
Default Options
By using the default option values, only the validity of the configured Yaml files are checked.
grunt.initConfig({ yaml_validator: { defaults: { src: 'configuration/*.yml', 'other/important/*_stuff.yml' } } });
Logging options
All output is written in the log file as well as to the standard output.
grunt.initConfig({ yaml_validator: { logged: { options: { log: 'yaml-validator.log' }, src: 'configuration/*.yml', 'other/important/*_stuff.yml' } } });
Structure validation options
In case an array is found, all its members are assumed to have the given structure.
This can be seen in the property, which according to the configuration below,
should be an array, for which all items are objects, which all should have a and
properties, with the given types.
The array is made of strings, thus all items in that array must be a string.
grunt.initConfig({ yaml_validator: { custom: { options: { structure: { school: { description: 'string', code: 'number', principal: { name: 'string' }, classRooms: { name: 'string', id: 'number' } , teachers: 'string' } } }, src: 'configuration/*.yml', 'other/important/*_stuff.yml' } } });
Warning callback in Yaml parsing options
Using the callback, the possible parsing errors can be retrieved.
grunt.initConfig({ yaml_validator: { custom: { options: { yaml: { onWarning: function (error, filepath) { console.log(filepath + ' has error: ' + error); } } }, src: 'configuration/*.yml', 'other/important/*_stuff.yml' } } });
Write a JSON file option
It is possible to use the to have all the files processed,
to be saved in JSON format, in the same file path as the original Yaml files.
grunt.initConfig({ yaml_validator: { custom: { options: { writeJson: true }, src: 'configuration/*.yml', 'other/important/*_stuff.yml' } } });
Outline Indentation and Whitespace
Whitespace is part of YAML’s formatting. Unless otherwise indicated, newlines indicate the end of a field.
You structure a YAML document with indentation. The indentation level can be one or more spaces. The specification forbids tabs because tools treat them differently.
Consider this document. The items inside stuff are indented with two spaces.
foo: bar pleh: help stuff: foo: bar bar: foo
Let’s take a look at how a simple python script views this document. We’ll save it as a file named foo.yaml.
The PyYAML package will map a YAML file stream into a dictionary. We’ll iterate through the outermost set of keys and values and print the key and the string representation of each value. You can find a processor for your favorite platform here.
import yaml if __name__ == '__main__': stream = open("foo.yaml", 'r') dictionary = yaml.load(stream) for key, value in dictionary.items(): print (key + " : " + str(value))
The output is:
foo : bar pleh : help stuff : {'foo': 'bar', 'bar': 'foo'}
When we tell python to print a dictionary as a string, it uses the inline syntax we’ll see below. We can see from the output that our document is a python dictionary with two strings and another dictionary nested inside it.
YAML’s simple nesting gives us the power to build sophisticated objects. But that’s only the beginning.
Usage
It’s method can be imported and used as below:
constvalidateSchema=require('yaml-schema-validator')validateSchema('path/to/target-file.yml',{ schemaPath'/path/to/required/schema.yml'})
The method automatically detects if file format is JSON or YAML and process it accordingly.
Similarly, method can also be used to validate plain JS objects:
let person ={ name{ first'Tom', last'Xoman'}, age45}vaidateSchema(person,{ schemaPath'/path/to/schema.yml'})constrequiredSchema={ name{ first{ typeString, requiredtrue}, last{ typeString, requiredtrue}}, age{ type Number}}schemaErrors =validateSchema(person,{ schema requiredSchema })
If you don’t have a schema object built, but you just want to compare if structure of two objects is same, then you can use option to pass the expected object:
let person ={ name{ first'Tom', last'Xoman'}, age'something'}let idealPerson ={ name{ first'Tom', last'Xoman'}, age45}vaidateSchema(person,{ schemaObj idealPerson })
Schema validator validates the target file against the passed schema and
lists down the mismatches in the structure:
It returns an array of errors showing the mismatches:
{path'person.id', message'person.id must be a String'}
Custom validators can be defined by passing an object with named validators to .use:
constcheckHexColor=val=>{return^#0-9a-fA-F$.test(val)}constcar=newSchema({ color{ typeString, use{ checkHexColor }}})
Define a custom error message for the validator:
car.message({checkHexColorpath=>`${path} must be a valid hex color.`})
Getting Started
This tool can be used in two ways, either via Node.js script, or as a command line tool.
Note that when used via command line, custom structure cannot be validated.
Installation when used via Node.js script:
npm install yaml-validator --save-dev
Installation when used as a command line tool:
npm install --global yaml-validator
Usage as a part of a Node.js script:
const YamlValidator = require('yaml-validator'); // Default options const options = { log: false, structure: false, onWarning: null, writeJson: false }; const files = 'file paths', 'that exists', 'somewhere', 'and are Yaml files' ; const validator = new YamlValidator(options); validator.validate(files); validator.report();
Using via command line tool, the only argument would be the Yaml file which should be validated:
yaml-validator random_file.yml
The available options for command line use, can be seen with the help command , which results in output similar to:
yaml-validator <files> -h, --help Help and usage instructions -V, --version Version number -w, --write-json Write the contents of the Yaml file to a JSON file next to it -l, --log-file String Log file where errors are written Version 2.0.0
When used from the command line, the process exits with the number of invalid files.
Indentation of block sequences¶
Although ruamel.yaml doesn’t preserve individual indentations of block sequence
items, it does properly dump:
x - b 1 - 2
back to:
x - b 1 - 2
if you specify (indentation is counted to the
beginning of the sequence element).
PyYAML (and older versions of ruamel.yaml) gives you non-indented
scalars (when specifying default_flow_style=False):
x - b 1 - 2
You can use to also have the mappings values indented.
The dump also observes an additional setting that
can be used to push the dash inwards, within the space defined by .
The above example with the often seen
indentation:
x y - b 1 - 2
The defaults are as if you specified .
If the equals , there is not enough
room for the dash and the space that has to follow it. In that case the
element itself would normally be pushed to the next line (and older versions
of ruamel.yaml did so). But this is
prevented from happening. However the level is what is used
for calculating the cumulative indent for deeper levels and specifying
resp. , might give correct, but counter
intuitive results.
It is best to always have
but this is not enforced. Depending on your structure, not following
this advice might lead to invalid output.
The «yaml_validator» task
In your project’s Gruntfile, add a section named to the data object passed
into .
grunt.initConfig({ yaml_validator{ options{}, your_target{ options{} src},},});
All options are by default which disables their use.
Type:
Default value:
In case the value is not , the given string will be used as log file where all the
task output is written.
Type:
Default value:
The most complex style of checking validity.
Type:
Default value:
Please note that the callback is being used by this plugin and any method written for it,
will be run after the one implemented in this plugin.
The callback get called with two parameters, of which the first is the error in question,
while the second is the file path of the given Yaml file.
Type:
Default:
Write the given Yaml file as pretty printed JSON in the same path, just by changing the file extension to .
Please note that any existing JSON files will be cruelly overwritten.
By using the default option values, only the validity of the configured Yaml files are checked.
grunt.initConfig({ yaml_validator{ defaults{ src'configuration/*.yml','other/important/*_stuff.yml'}}});
All output is written in the log file as well as to the standard output.
grunt.initConfig({ yaml_validator{ logged{ options{ log'yaml-validator.log'}, src'configuration/*.yml','other/important/*_stuff.yml'}}});
In case an array is found, all its members are assumed to have the given structure.
This can be seen in the property, which according to the configuration below,
should be an array, for which all items are objects, which all should have a and
properties, with the given types.
The array is made of strings, thus all items in that array must be a string.
grunt.initConfig({ yaml_validator{ custom{ options{ structure{ school{ description'string', code'number', principal{ name'string'}, classRooms{ name'string', id'number'}, teachers'string'}}}, src'configuration/*.yml','other/important/*_stuff.yml'}}});
Using the callback, the possible parsing errors can be retrieved.
grunt.initConfig({ yaml_validator{ custom{ options{ yaml{onWarningfunction(error,filepath){console.log(filepath +' has error: '+ error);}}}, src'configuration/*.yml','other/important/*_stuff.yml'}}});
It is possible to use the to have all the files processed,
to be saved in JSON format, in the same file path as the original Yaml files.
grunt.initConfig({ yaml_validator{ custom{ options{ writeJsontrue}, src'configuration/*.yml','other/important/*_stuff.yml'}}});
Синтаксис YAML¶
Как и Python, YAML использует отступы для указания структуры документа.
Но в YAML можно использовать только пробелы и нельзя использовать знаки
табуляции.
Еще одна схожесть с Python: комментарии начинаются с символа # и
продолжаются до конца строки.
Список
Список может быть записан в одну строку:
switchport mode access, switchport access vlan, switchport nonegotiate, spanning-tree portfast, spanning-tree bpduguard enable
Или каждый элемент списка в своей строке:
- switchport mode access - switchport access vlan - switchport nonegotiate - spanning-tree portfast - spanning-tree bpduguard enable
Когда список записан таким блоком, каждая строка должна начинаться с
(минуса и пробела), и все строки в списке должны быть на одном
уровне отступа.
Словарь также может быть записан в одну строку:
{ vlan 100, name IT }
Или блоком:
vlan 100 name IT
Строки
Строки в YAML не обязательно брать в кавычки. Это удобно, но иногда всё
же следует использовать кавычки. Например, когда в строке используется
какой-то специальный символ (специальный для YAML).
Такую строку, например, нужно взять в кавычки, чтобы она была корректно
воспринята YAML:
command "sh interface | include Queueing strategy:"