如何在JSON模式中使用定义(draft-04)

时间:2013-08-22 08:41:37

标签: json jsonschema

我正在使用的其余服务响应类似于以下示例,我在这里仅包含3个字段,但还有更多:

{
    "results": [
        {
            "type": "Person",
            "name": "Mr Bean",
            "dateOfBirth": "14 Dec 1981"
        },
        {
            "type": "Company",
            "name": "Pi",
            "tradingName": "Pi Engineering Limited"
        }
    ]
}

我想为上面的(draft-04)编写一个JSON模式文件,它将明确指定:

if type == Person then list of required properties is ["type", "name", "dateOfBirth", etc] 
OR
if type == "Company" then list of required properties is ["type", "name", "tradingName", etc]

但是我无法找到任何文档或如何操作的示例。

目前我的JSON架构如下所示:

{
    "$schema": "http://json-schema.org/draft-04/schema",
    "type": "object",
    "required": ["results" ],
    "properties": {
        "results": {
            "type": "array",
            "items": {
                "type": "object",
                "required": ["type", "name"],
                "properties": {
                    "type": { "type": "string" },
                    "name": { "type": "string" },
                    "dateOfBirth": { "type": "string" },
                    "tradingName": { "type": "string" }
                }
            }
        }
    }
}

我应该如何处理这个问题的任何指针/示例。

2 个答案:

答案 0 :(得分:33)

我认为推荐的方法是Json-Schema web, Example2中显示的方法。您需要使用枚举“按值”选择模式。在你的情况下,它将是这样的:

{
    "type": "object",
    "required": [ "results" ],
    "properties": {
        "results": {
            "type": "array",
            "items": {
                "oneOf": [
                    { "$ref": "#/definitions/person" },
                    { "$ref": "#/definitions/company" }
                ]
            }
        }
    },
    "definitions": {
        "person": {
            "properties": {
                "type": { "enum": [ "person" ] },
                "name": {"type": "string" },
                "dateOfBirth": {"type":"string"}
            },
            "required": [ "type", "name", "dateOfBirth" ],
            "additionalProperties": false
        },
        "company": {
            "properties": {
                "type": { "enum": [ "company" ] },
                . . . 
            }        
        }
    }
}

答案 1 :(得分:10)

对不起,

我不明白这一点。问题是关于'dependencies'关键字,它是最后一个JSON Schema规范的一部分,对吗?

我在接受的答案中找不到“依赖”(?)

在最后的草案中对其进行了简要说明。 但http://usingjsonschema.com解释了本书中的属性和定义依赖关系:

http://usingjsonschema.com/assets/UsingJsonSchema_20140814.pdf

从第29页开始(参见第30页解释)

"dependencies": {
     "shipTo":["shipAddress"],
     "loyaltyId":["loyaltyBonus"]
}