JSON 架构 : Require properties on an optional object type

标签 json jsonschema

我在我的 json 模式中定义了一个客户对象类型:

"customer": {
    "type": "object",
    "properties": {
      "id": { "type": "string" },
      "first_name": { "type": "string" },
      "last_name": { "type": "string"},
      "email": { "type": "string" },
      "billing_address": { "$ref": "#\/definitions\/street_address" },
      "shipping_address": { "$ref": "#\/definitions\/street_address" },
    },
    "required": [ "id", "first_name", "last_name", "email", "billing_address"]
  },

我想验证 shipping_address (可选对象)是否已发送,如果缺少必填字段则拒绝它。这是 street_address 对象定义:
"street_address": {
    "type": "object",
    "properties": {
      "first_name": {"type": "string" },
      "last_name": { "type": "string" },
      "address": { "type": "string" },
      "address2": { "type": "string" },
      "city": { "type": "string" },
      "state": { "type": "string" },
      "zip_code": { "type": "string"},
      "country_code": { "type": "string"},
      "phone": { "type": "string"},
      "fax": {"type": "string"}
    },
    "required": [
      "first_name",
      "last_name",
      "address",
      "city",
      "state",
      "zip_code",
      "country_code"
    ]
  },

如何配置我的 JSON 模式来完成此操作?当我现在发送送货地址时,对象内的字段不会得到验证。

最佳答案

您正在使用引用 "$ref": "#\/definitions\/street_address" (顺便说一句,你不必逃避斜线)。在这种情况下, street_address 定义必须在同一个文档中,在“defintions”节点内。所以你的架构文件看起来像这样

   {
    "$schema": "http://json-schema.org/draft-04/schema#",
    "title": "customer",
    "type": "object",
    "properties": {
      "id": { "type": "string" },
      "first_name": { "type": "string" },
      "last_name": { "type": "string"},
      "email": { "type": "string" },
      "billing_address": { "$ref": "#/definitions/street_address" },
      "shipping_address": { "$ref": "#/definitions/street_address" },
    },
    "required": [ "id", "first_name", "last_name", "email", "billing_address"],
    "definitions" : {
        "street_address" : { 
             /* here comes the street_address definition */ 
        },
        /* other entity definitions */
     }

  }

我正在使用 nodejs 模块 jayschema (参见 https://github.com/natesilva/jayschema )进行验证,这样就可以正常工作。

关于JSON 架构 : Require properties on an optional object type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25019023/

相关文章:

json - 使用Chrome的开发工具调试JSON

php - 在页面加载时获取json文件的内容

java - 使用 jsonschema2pojo 或 com.sun.codemodel 时在类的开头添加注释

ios - 通过在 Swift iOS 中解析 JSONschema 保存字典中键的原始顺序

尽管类型正确,json 模式验证仍失败

ruby-on-rails - Rails 无法正确呈现来自 Postgres JSON 函数的嵌套 JSON 结果

java - 在JAVA中读取JSON数组

基于属性之一的 JSON 模式 anyOf 验证

javascript - JSON解析: Uncaught SyntaxError: Unexpected token e

javascript - JSONSchema 和验证子对象属性