英文:
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中可以实现以下功能的库吗:
- 验证所有响应字段是否在模式中
- 如果模式中的字段不在响应中,不会导致验证失败
英文:
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:
- validate that all the response fields are in the schema
- 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论