How to validate with schema id?
Closed this issue · 2 comments
kondaurovDev commented
I don't understand how to validate json when you have schema id
For eg, i added many schemas automatically to SchemaValidator
val validator = new SchemaValidator(Some(Version7))
val schema1: SchemaType = Json.fromJson('{"$id": "foo", "type": string}').get
val schema2: SchemaType = Json.fromJson('{"$id": "bar", "type": string}').get
validator.addSchema(schema)
And finally i want to validate like that: validator.validate("foo", ""my json input"")
I don't want to instantiate SchemaType for foo
edgarmueller commented
I think what you ask for is currently not possible, since you need a schema, but we could add support for validating based on $id in the future. addSchema
right now is used to make schemas known to the validator when using $refs, so the schema should contains the respective
$ref` you want to validate against. Your example right now would look as follows:
val schema1: SchemaType = JsonSource.schemaFromString(
"""
|{ "type": "string" }
""".stripMargin
).get
val schema2: SchemaType = JsonSource.schemaFromString(
"""
|{ "type": "number" }
""".stripMargin
).get
val validator = SchemaValidator(Some(Version7))
.addSchema("foo", schema1)
.addSchema("bar", schema2)
val schemaFoo = JsonSource.schemaFromString(
"""
|{ "$ref": "foo" }
""".stripMargin).get
val schemaBar = JsonSource.schemaFromString(
"""
|{ "$ref": "bar" }
""".stripMargin).get
val schemaBaz = JsonSource.schemaFromString(
"""
|{ "$ref": "baz" }
""".stripMargin).get
// these succeed
validator.validate(schemaFoo, JsString("foo")).isSuccess must beTrue
validator.validate(schemaBar, JsNumber(42)).isSuccess must beTrue
// these fail because of wrong types
validator.validate(schemaFoo, JsNumber(42)).isError must beTrue
validator.validate(schemaBar, JsString("foo")).isError must beTrue
// these fail because baz can not be resolved
validator.validate(schemaBaz, JsString("foo")).isError must beTrue
validator.validate(schemaBaz, JsNumber(42)).isError must beTrue
Does this help?
edgarmueller commented
Closing due to inactivity.