使用Golang进行可选字段的JSON模式验证

huangapple go评论97阅读模式
英文:

JSON schema validation of optional fields using Golang

问题

Golang的JSON模式验证库可以验证服务请求/响应中的模式中是否存在所需字段。

我需要验证服务请求或响应中的任何字段都必须是模式上的属性。如果有效载荷中的属性在模式中不存在,验证应该失败。

例如:一个GET响应:

{
   "pet": "dog",
   "name": "Scooby",
   "licence": "123-123"
}

在我的示例JSON模式中,没有字段是必需的。然而,如果我在服务中将字段"pet"改为"petBreed",它将不会被JSON模式验证器(例如https://github.com/xeipuuv/gojsonschema)捕获到。

将所有字段设置为必需的不是一个选项。有人可以建议一个在Go中可以实现以下功能的库吗:

  1. 验证所有响应字段是否在模式中
  2. 如果模式中的字段不在响应中,不会导致验证失败
英文:

Golang JSON schema validation libraries validate that required fields on the schema are present in the service request/response.

I need to validate that any field in a service request or response must be a property on the schema. If a property in the payload does not exist in the schema, the validation should fail.

For example: a GET response:

{
   "pet": "dog",
   "name": "Scooby",
   "licence": "123-123"
}

In my sample JSON schema, none of the fields are required. However, if I changed the field "pet" to "petBreed" in my service, it will not be caught by a JSON schema validator (e.g. https://github.com/xeipuuv/gojsonschema).

Making all fields required is not an option. Can anyone suggest a library in Go that will:

  1. validate that all the response fields are in the schema
  2. not fail if a field from the schema isn't in the response

答案1

得分: 3

JSON Schema为此目的定义了additionalProperties,类似于以下模式应该可以工作:

{
    "type": "object",
    "additionalProperties": false,
    "properties":{
        "pet": ...,
        "name": ...,
        "license": ...,
    },
}

这在gojsonschema中已经实现,但在文档中没有明确说明。

请注意,additionalProperties是一个模式,不仅仅是一个布尔值,也就是说,您可以对未知属性进行任意验证,而不仅仅是禁止它们。

英文:

JSON Schema defines additionalProperties for this purpose, something like this schema should work:

{
    "type": "object",
    "additionalProperties": false,
    "properties":{
        "pet": ...,
        "name": ...,
        "license": ...,
    },
}

This is implemented but not documented as such in gojsonschema.

Note that additionalProperties is a schema, not just a boolean, i.e. you can do arbitrary validation of unknown properties, not just disallow them.

huangapple
  • 本文由 发表于 2017年5月15日 18:52:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/43977640.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定