YAML vs JSON
JSON
JSON(JavaScript Object Notation) is wildly used for a client and a server communication. It is a simpler way to represent the data compared to XML(Extensible Markup Language). As you can see the below example, JSON is significantly less verbose than XML. Especially, there is no opening and closing tags in JSON.
JSON
XML
YAML
YAML(YAML Ain’t Markup Language) gives a even simpler way than JSON to represent the data. It removes curly brackets({}
) and squard brackets([]
) except for inline collections. In addition, vertical alignment is used to show the structure. Technically, YAML is a superset of JSON. In most cases, it is possible to convert YAML to JSON and JSON to YAML. YAML also has extra features, which are not in JSON.
- Commenting: Adding additional information as a comment
- Aliasing and Anchoring: Giving an alias to an item and referring it instead of typing/repeating many times
- Merging: Merging aliased item into a current map
YAML
Basic Syntax
Here are basic syntaxes of YAML. I’ve added an equivalent JSON data so that you can compare between YAML and JSON.
Sequence
You can specify a sequence using -
. You can nest a sequence with an empty -
, followed by an indented sequence.
YAML
JSON
Mapping
You can specify a key-value map using :
. Each member of the map should be on a new line.
YAML
JSON
Inline Sequence
You can make a sequence in a short way. Like JSON, []
is used for the inline sequence.
YAML
JSON
Inline Mapping
You can make a map like a JSON way with {}
.
YAML
JSON
Aliasing and Anchoring
You can give an alias to a specific item using &
and name. Then, you can refer/anchor it with *
and its name.
YAML
JSON
Aliasing and anchoring is possible not only for a value but also for a whole item.
YAML
JSON
Merging
If you alias a map, you can merge that into the current map with <<
.
YAML
JSON
Multilines
You can put multilines just by adding it. In this case, one line break is ignored and consider it as one line. In this example, there is no \n
between serialization and standard.
YAML
JSON
If you want to keep every line break, you can specify it using |
with an indented block. This is treated as a literal block.
YAML
JSON
Commenting
You can specify a comment using #
to add an additional information.
YAML
JSON
Conclusion
YAML has good extra features such as commenting, aliasing and anchoring. It is super human-readable. Compared to YAML, JSON is a bit limited. However, JSON is widely used and supported. One of the main reasons is that it is faster to serialize and deserialize, which is a key factor to communicate between a client and a server. Check this benchmark. To sum up,
- Use JSON for communication between a client and a server.
- Use YAML for configuration files since YAML is really human-readable.
If you want to try/learn YAML, this YAML to JSON online site is quite handy.