Mecha CMS

Mecha CMS blog and documentation.

YAML

Updated: Sunday, 07 August 2016

YAML–like string parser.

To store array in YAML format or to convert YAML–like data format into array is possible in Mecha but it is limited only to key: value–based syntax to mimic array keys and their values. You can’t parse external YAML files anyway with Mecha’s internal string parser. But the YAML–like data generated by Converter::toText() basically can be treated as a valid YAML data in most cases.

Converter

String to Array

$results = Converter::toArray('foo: bar');

Array to String

$results = Converter::toText(array('foo' => 'bar'));

Related: Class Converter

Syntax

Keys and Values

foo: bar
baz: qux
{
  "foo": "bar",
  "baz": "qux"
}

Empty Values

foo:
bar: ''
baz: ""
{
  "foo": [],
  "bar": "",
  "baz": ""
}

Empty Data

[]

Comments

# comment
test_1: foo
test_2: foo # comment
test_3: 'foo # comment' # comment
test_4: "foo # comment" # comment
test_5: # comment 'foo'
test_6: # comment "foo"
{
  "test_1": "foo",
  "test_2": "foo",
  "test_3": "foo # comment",
  "test_4": "foo # comment",
  "test_5": [],
  "test_6": []
}

Nesting

a: b
c: d
e:
    f: g
    h: i
j: k
{
  "a": "b",
  "c": "d",
  "e": {
    "f": "g",
    "h": "i"
  },
  "j": "k"
}

Sequential Arrays

Arrays with numeric keys.

Manual
0: a
1: b
2: c
["a", "b", "c"]
Automatic
: a
: b
: c
["a", "b", "c"]

No Keys

List of data without keys will be converted into key: key.

a
b
c
{
  "a": "a",
  "b": "b",
  "c": "c"
}

Data Types

All data types will be converted automatically by Converter::strEval().

string: a
integer: 1
float: 1.5
boolean: true
null: null
JSON: {"foo":"bar","baz":"qux","integer":"1","boolean":"false"}
string_integer: "1"
string_float: "1.5"
string_boolean: "true"
string_null: "null"
single_quote: 'foo\nbar'
double_quote: "foo\nbar"
{
  "string": "a",
  "integer": 1,
  "float": 1.5,
  "boolean": true,
  "null": null,
  "JSON": {
    "foo": "bar",
    "baz": "qux",
    "integer": 1,
    "boolean": false
  },
  "string_integer": "1",
  "string_float": "1.5",
  "string_boolean": "true",
  "string_null": "null",
  "single_quote": "foo\\nbar",
  "double_quote": "foo\nbar"
}
array(
    'string' => 'a',
    'integer' => 1,
    'float' => 1.5,
    'boolean' => true,
    'null' => null,
    'JSON' => array(
        'foo' => 'bar',
        'baz' => 'qux',
        'integer' => 1,
        'boolean' => false
    ),
    'string_integer' => '1',
    'string_float' => '1.5',
    'string_boolean' => 'true',
    'string_null' => 'null',
    'single_quote' => 'foo\nbar',
    'double_quote' => 'foo
bar'
)

Escaping

foo\:bar: baz
foo: bar: baz
{
  "foo:bar": "baz",
  "foo": "bar: baz"
}
Donation and Email Subscription