JSON-schema:基于oneOf的值

时间:2016-12-11 18:34:38

标签: json schema jsonschema

我有以下json-schema定义了3种类型的玩具,与json GUI buildergithub)一起使用:

{
    "id": "http://some.site.somewhere/entry-schema#",
    "$schema": "http://json-schema.org/draft-04/schema#",
    "description": "schema for toys in game",
    "type": "object",
    "required": [ "type" ],
    "properties": {
        "sawObj": {
            "type": "object",
            "oneOf": [
                { "$ref": "#/definitions/rect" },
                { "$ref": "#/definitions/circle" },
                { "$ref": "#/definitions/img" }
            ]
        }
    },
    "definitions": {
        "rect": {
            "properties": {
                "width": { "type": "integer" },
                "height": { "type": "integer" },
                "weight": { "type": "integer" }
            },
            "required": [ "width", "height", "weight" ],
            "additionalProperties": false
        },
        "circle": {
            "properties": {
              "radius": { "type": "integer" },
              "weight": { "type": "integer" }
            },
            "required": [ "radius", "weight" ],
            "additionalProperties": false
        },
        "img": {
            "properties": {
              "path": { "type": "string" },
              "width": { "type": "integer" },
              "height": { "type": "integer" },
              "weight": { "type": "integer" }
            },
            "required": [ "path", "width", "height", "weight" ],
            "additionalProperties": false
        }
    }
}

如果我选择圆形对象,例如我得到一个输出:

{
  "sawObj": {
    "radius": 0,
    "weight": 0
  }
}

我想添加一个值“type”,它总是被约束以反映用户选择的类型。所以改为这样:

{
  "sawObj": {
    "type": "circle",
    "radius": 0,
    "weight": 0
  }
}

其中类型由oneOf属性部分中的用户选择自动确定。

如何使用json-schema执行此操作?

1 个答案:

答案 0 :(得分:0)

我能够执行此枚举值,并且只允许表示该类型的单个值。我还根据需要设置了类型值,因此它总是自动设置为' circle'。

"circle": {
    "properties": {
        "radius": {
            "type": "integer"
        },
        "weight": {
            "type": "integer"
        },
        "type": {
            "type": "string",
            "enum": ["circle"]
        }
    },
    "required": ["radius", "weight", "type"],
    "additionalProperties": false
}

注意:我想指出这个解决方案并不理想。我希望找到一个更好的方法来做到这一点。