dtdb99743 2017-05-15 10:52
浏览 860
已采纳

使用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 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?