【问题标题】:JSON-schema: value based on oneOfJSON模式:基于oneOf的值
【发布时间】:2017-04-26 15:44:30
【问题描述】:

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

{
    "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 做到这一点?

【问题讨论】:

    标签: json schema jsonschema


    【解决方案1】:

    我能够对枚举值执行此操作,并且只允许一个表示类型的值。我还根据需要设置了类型值,因此它总是自动设置为“圆”。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-31
      • 1970-01-01
      • 2020-02-03
      • 2017-06-02
      • 1970-01-01
      • 2016-10-17
      • 1970-01-01
      相关资源
      最近更新 更多