JSON模式:需要可选对象类型的属性

时间:2014-07-29 15:22:28

标签: 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架构来完成此任务?当我现在发送送货地址时,对象内的字段不会被验证。

1 个答案:

答案 0 :(得分:1)

你正在使用引用"$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)进行验证,它可以正常工作。