Yes, it's allowed by the YAML spec, latest version 1.2.2: https://yaml.org/spec/1.2.2/.
The same examples that you posted appear on the spec's section on 2.1 Collections:
Example 2.2 Mapping Scalars to Scalars (player statistics)
hr: 65 # Home runs
avg: 0.278 # Batting average
rbi: 147 # Runs Batted In
The full comment specs has its own section, 6.6 Comments. The main rules are that it starts with a #
and "must be separated from other tokens by white space characters". It can also span multiple lines.
firstName: john # comment line 1
# comment line 2
lastName: doe
As for knowing if it would work and
I have no way to test this
You can use any of the popular YAML linters (based on your comment, see What is "Linting"?). It can either be a command-line tool (like yq
), a website (like YAMLlint), an integrated tool on where you would be using your YAML file (like Gitlab's CI Lint Tool), an extension on your IDE/editor, or some language-specific library (like ruamel.yaml
for Python as demonstrated by this answer on a related question).
On YAMLlint, it shows your YAML as valid, but it strips out the comments because it "give you a nice clean UTF-8 version of it." (also, as the YAML spec says, "Comments are a presentation detail" only and "must not be used to convey content information". Processors should just ignore them). The image does show the payload to the site included the comments, and the site responded with 200/OK:

I personally use the yq
command line utility.
$ cat test.yaml
# profile fields
firstName: string
lastName: string
phoneNum: string # optional
active: boolean
notes: string # optional
role: string # admin | market | client
by: User_Id
$ yq '.role' test.yaml
string
$ cat invalid.yaml
key1: [value2]
key2: key3: key4: value3
$ yq '.key2' invalid.yaml
Error: bad file 'invalid.yaml': yaml: line 2: mapping values are not allowed in this context