如何针对摇摇欲坠的模式验证JSON模式的实例?

问题描述:

I have a JSON payload (request or response) and I want to validate that instance against a swagger schema that I have. How do I do that?

Please note that I am not trying to validate if my spec is an OpenAPI/Swagger spec.

I'd like to achieve this without the use of external JSON validators. I am also trying to achieve this in Go (specifically go-openapi)

Thanks.

我有一个JSON有效负载(请求或响应),我想根据我拥有的大摇大摆的模式来验证该实例 。 我该怎么做? p>

请注意,我不是要验证我的规格是否为OpenAPI / Swagger规格。 p>

我希望 想要在不使用外部JSON验证器的情况下实现这一目标。 我也在尝试在Go(特别是go-openapi)中实现这一目标 p>

谢谢。 p> div>

You need to get a hold of the schema that defines your validation rules, that's typically stored in the swagger spec definition property.

And you need to get your model (json data structure, can be a map or a struct). Here's an example:

var model models.User
json.Unmarshal(bytes, &model)

var spec *spec.Swagger = getSpec()
schema := spec.Definitions["User"]

if err := validate.AgainstSchema(schema, &model, strfmt.Default); err != nil {
  return err
}