dtdb99743
dtdb99743
2017-05-15 10:52
浏览 270

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

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条回答 默认 最新

  • douyan2002
    douyan2002 2017-05-15 15:43
    已采纳

    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.

    点赞 评论

相关推荐