Validate YAML against a Schema in C#

Viewed 814

I have some YAML files, and I want to define a schema and then validate the YAML against the schema before trying to work with it in C#.

From my research there doesn't appear to be a schema language specific for YAML, but people use JSON Schema to validate YAML files. So that's what I tried.

The Yaml library I'm using (YamlDotNet) doesn't appear to be able to do schema validation, so I tried to do what I saw in some other examples. Convert the YAML to JSON then use Newtonsoft.Json to validate against my schema.

var schemaJson = File.ReadAllText(schemaPath);
var schema = Newtonsoft.Json.Schema.JSchema.Load(new JsonTextReader(new StringReader(schemaJson)));

var deserializer = new YamlDotNet.Serialization.Deserializer();
var data = deserializer.Deserialize(new StringReader(yaml));

var sb = new StringBuilder();
var sw = new StringWriter(sb);

var serializer = new Newtonsoft.Json.JsonSerializer();
serializer.Serialize(sw, data);

Newtonsoft.Json.Linq.JObject.Parse(sb.ToString()).Validate(schema);

The problem with this is when I deserialize the YAML, it stuffs the data into a Dictionary, and ultimately every value is a string. So when I serialize back to JSON all the values get wrapped in single quotes, and when I try to validate against my schema, anything that the schema says is an integer/number will fail.

e.g. This YAML:

name: John Doe
age: 27

will get converted to JSON something like this:

{
  name: 'John Doe'
  age: '27'
}

And when I try to validate against my JSON Schema that says age should be an integer that fails.

1 Answers

Yes, you can use JSON Schemas to validate data from YAML files, as the data model that YAML is uses is very close (but not identical) to JSON. And most JSON Schema evaluators tend to work with deserialized data anyway, after it has been decoded from JSON or any other data format that uses a similar data model.

Your problem sounds like a misconfiguration in your YAML deserializer. The YAML format is capable of differentiating strings from numbers, so the serializer should do so as well, or at least offer different options for handling strings that look like numbers.

Related