What the YAML Formatter does
The YAML Formatter parses YAML and writes it out again with consistent two-space indentation and normalised quoting. Because it rewrites from the parsed data, comments are not kept.
YAML Formatter examples
The built-in sample
Input
name: Ada
tags: [math, code]
address: {city: London}Output
name: Ada
tags:
- math
- code
address:
city: London
This is the input that the Load sample button fills in.
Long strings, flow collections and quotes
Input
msg: "This is a long sentence that keeps going well past eighty characters so that the dumper has to decide what to do with it."
list: [1, 2, {a: b}]
quoted: "yes"
ver: "1.10"
multi: "line one\nline two"Output
msg: >-
This is a long sentence that keeps going well past eighty characters so that
the dumper has to decide what to do with it.
list:
- 1
- 2
- a: b
quoted: 'yes'
ver: '1.10'
multi: |-
line one
line two
The long string is folded with >- at 80 columns, the inline list is expanded to block style, double quotes become single quotes where quotes are needed at all, and the string with a line break becomes a literal block.
Anchors and comments
Input
version: 1.10
enabled: yes
released: 2024-01-05
base: &b
retries: 3
prod: *b
host: ~
# trailing commentOutput
version: 1.1
enabled: 'yes'
released: 2024-01-05T00:00:00.000Z
base: &ref_0
retries: 3
prod: *ref_0
host: null
The comment is gone. The anchor survives, but under a generated name (&ref_0), and the unquoted date comes back as a full timestamp. The word yes is now quoted because it is a string.
Each output was produced by running this tool on the input above it.
How it works
js-yaml parses the input and reports errors with a line and column. The parsed data is then written out again with two-space indentation. Comments are not part of the parsed data, so they are not kept, and quoting is normalised.
Details and limits
- Indentation is two spaces and list items are indented under their key.
- Key order is preserved; nothing is sorted.
- A mapping that is referenced through an alias keeps being shared, but the anchor is renamed to
ref_0,ref_1and so on. - Because comments and blank lines are not kept, do not use this on hand-maintained files where they matter. Use the YAML Validator to check those without rewriting them.
- Input that is not valid YAML stops the tool, and the status line shows where the problem is. The YAML Validator page lists the usual causes.
Questions
Are comments preserved?
No. The file is rebuilt from the parsed data, and comments are not part of that data.