我在我的 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/