gregsdennis/Manatee.Json

Loading JSON schemas from a file for validation

ikenne opened this issue · 3 comments

Hi,

I was checking the API to see if there is an option to load a defined JSON schema from a file, and then using this to validate JSON input (say in a string), but have not seen such an option.

Is this currently supported?

Yes, it is supported. In fact, this is how the JSON Schema Test Suite is validated.

To get an instance of the schema, you can use one of two methods

  1. JsonSchemaRegistry.Get() - For this, you need to pass the file name in a URI format, which means that you'll need the file:/// protocol as a prefix.
    var schema = JsonSchemaRegistry.Get("file:///c:\schema.json");
  2. Manual parse & load - You can also manually read the file text, parse the JSON and then deserialize a schema from that. (This is done internally in method 1.)
    var schemaText = File.ReadAllText("c:\schema.json");
    var schemaJson = JsonValue.Parse(schemaText);
    var schema = new JsonSerializer().Deserialize<IJsonSchema>(schemaJson);

Regardless of which method you choose, be sure you're getting the right schema draft. Manatee.Json will attempt to figure out which version is correct based on the the content of the schema, but you can be sure by setting the default draft.

Once you have the schema, you need to pass it a JsonValue of the JSON you want to validate. To get this, you can use JsonValue.Parse().

var json = "<json text>";
var results = schema.Validate(json);

For more info, you can check the tests in this repository and in the docs. I'll try to expand the docs to show more extensive usage of schema.

For what it's worth, I typically use method 2 because I don't like formatting file URIs.

Thank you for the prompt response.

Method 2 fits better to what I'm trying with a couple of other libraries, so I will probably use that.

With regards to schema draft, I think draft 6 will be better for my purpose. My current schema uses the "propertyNames": see "Additions and backwards-compatible changes" here: http://json-schema.org/draft-06/json-schema-release-notes.html
Does the library support this?

Yes, drafts 4, 6, and 7 are fully supported.

Please feel free to read the documentation for more information.