【问题标题】:JSON schema - possible to reference multiple schemas from one object?JSON 模式 - 可以从一个对象引用多个模式吗?
【发布时间】:2015-06-29 03:15:12
【问题描述】:

以下是我的 JSON 架构的摘录。

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "object",
    "properties": {
        "images": {
            "type": "array",
            "items": { "$ref": "#/definitions/bits" },
        }
    },
    "definitions": {
        "identifier": {
            "type": "string"
        },
        "bits": {
            "type": "integer",
            "enum": [
                8,
                16,
                32
            ]
        }
    }
}

按照说明,我相信一个图像数组,其中每个元素由一个字符串标识符和一个整数组成,其值可以是 8、16 或 32,将被视为有效的 JSON 数据。

这对我的一些 JSON 数据来说很好。

但是,如果我想进一步限制模式,使整数值只能是 32,该怎么办?我将如何做到这一点,同时仍然允许一些 JSON 数据对原始模式有效?

是否有可能,例如,在一个对象中引用两个模式,例如类似:

items": { "$ref": "#/definitions/bits" AND "$ref": "#/definitions/otherSchema"}

【问题讨论】:

    标签: json schema jsonschema


    【解决方案1】:

    您可以使用allOf 来验证多个架构。

    {
        "items": {
            "allOf": [
                { "$ref": "#/definitions/bits" },
                { "$ref": "#/definitions/otherSchema" }
            ]
        }
    }
    

    【讨论】:

    • 如果 otherSchema 定义bits 为32,你是说上面的语法会给我我想要的吗?它不会被视为两个独立的属性吗?
    • 是的,allOf 中的所有架构都适用于同一个架构。在这种情况下,数组中的所有项目都必须针对allOf 中的两种模式进行验证。 oneOfanyOfnot 是其他可用于同时引用多个架构的关键字。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-30
    • 2014-03-23
    • 2017-06-09
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    相关资源
    最近更新 更多