You can think of YAML as a superset of JSON. Any JSON document can be easily converted to YAML.
The JSON types are
- null
- boolean
- number
- string
- object
- array
Here are examples of each of these in JSON followed by its YAML representation
Identical in JSON and YAML
JSON:
null
YAML:
null
Identical in JSON and YAML
JSON:
true
YAML:
true
Identical in JSON and YAML
JSON:
1.5
YAML:
1.5
Quotes in YAML are optional or when needed to make type explicit. Also you can use single or double quotes. Are formatter defaults to single quotes. So if you use double quotes prettier will change them to single quotes.
JSON:
"Michael"
YAML:
Michael
But now let's assume that we have a string of "1.23"
. If we didn't use quotes
in YAML then it would be assumed to be a number. So we use quotes to be explicit
that it's a string.
"1.23"
YAML:
'1.23'
Objects in YAML don't use curly braces. There are exceptions. For example I've
seen and used {}
as a short hand representation of an empty object in YAML.
Perhaps you can even use them exactly as you do in YAML but that's not what is
typically done. Also the keys in objects in YAML don't require quotes.
Also, we don't use commas between properties. End of line is sufficient.
JSON:
{
"firstName": "Michael",
"lastName": "Welch"
}
YAML:
firstName: Michael
lastName: Welch
It can get a little tricker with nested objects where we use indentation.
JSON
{
"firstName": "Michael",
"lastName": "Welch",
"address": {
"street": "123 Main St",
"state": "WI",
"zip": "55555"
}
}
YAML:
firstName: Michael
lastName: Welch
address:
# note the indentation for nested object
street: 123 Main St
state: WI
zip: '55555' # note the use of quotes to ensure this is a string
Arrays don't use []
or commas. (Although you can use that syntax. Prettier
will actually convert between the two based on size I think)
JSON:
["red", "green", "blue"]
YAML
- red
- green
- blue
Where it can get tricky is arrays of objects and arrays in an object as we need to use indentation.
JSON object with array values
{
"name": "michael",
"interests": ["movies", "card games", "tech"]
}
Now in YAML
name: michael
interests:
- movies
- card games
- tech
Now let's do an array of objects
JSON:
{
"name": "tom",
"age": 50,
"children": [
{
"name": "bill",
"age": 20
},
{
"name": "susan",
"age": 18
}
]
}
Now in YAML
name: tom
age: 50
children:
# notice we indent for the array, but then we also indent for every
# property of the nested object
- name: bill
age: 20
- name: susan
age: 18