Unlike JSON, YAML allows an object's keys to be anything, like arrays or objects. (reference)
Is it possible to write a schema for YAML that defines what the keys should be like? For example
mapping:
# accepted: each key must be an array of ints
? - 2
- 3
: okay
# not accepted
? - hello
- world
: not okay
or
mapping:
# accepted: each key must be an object
# with a field called "value", whose value is a string
? value: hello world
: okay
# not accepted
? hello: world
: not okay
I'm familar with writing JSON schemas, which also work for YAML as long as the target yaml doesn't use any such "advanced" features. But I don't know if something like this, which is beyond JSON, is possible.
Is it possible to write a schema for YAML that defines what the keys should be like?
Technically yes, but not with every implementation.
You can argue based on the YAML spec's definition of a schema that implementations in statically typed languages (e.g. SnakeYAML for Java, go-yaml for Go, NimYAML for Nim, ...) use the native types they deserialize into as schema. So if you deserialize into, e.g., Map<ComplexKey, Value>
that would be a schema that defines the structure of keys by means of the type ComplexKey
.
However, your use-case is possibly a different one. For example, a common definition of schema is „a structural definition I can validate a YAML file against with a command-line tool or editor plugin“. If this is your use-case, then what I described in the previous paragraph is of no use to you – as you would need to compile a tool based on that for each schema you want to validate against.