Is XML Schema xs:alternative equivalent available in JSON Schema?

十年热恋 提交于 2019-12-10 16:15:19

问题


Is it possible to use alternatives in JSON Schema? In XSD this is doable using xs:alternative element.

For example see: How to use alternatives in XML Schema 1.1


UPDATE 1:

This is a sample JSON I would like to describe using JSON schema:

{
  "actions": [
    {
      "type": "basic",
      "param1": "value"
    },
    {
      "type": "extended",
      "param1": "value",
      "param2": "blah"
    }
  ]
}

Requirements:

  • actions may have any number of items
  • basic actions must contain param1 property
  • extended actions must contain param1 and param2 properties

回答1:


There is a similar mechanism since Draft04 with nicer semantics: oneOf, anyOf, allOf and not, keywords.

  • oneOf: enforce a given element to satisfy only one of a list of schemas.
  • anyOf: must satisfy at least one of a list of schemas.
  • allOf: must satisfy all provided schemas in list.
  • not: must not satisfy a given schema.

Assuming you are looking for an exclusive "alternative", this would be an example of json-schema using oneOf:

{
    "actions" : {
        "type" : "array",
        "items" : {
            "oneOf" : [{
                    " $ref " : "#/definitions/type1 "
                }, {
                    " $ref " : "#/definitions/type2 "
                }
            ]

        }

    },
    " definitions " : {
        " type1 " : {
            " type " : " object ",
                        "properties": {
                                  "param1":{"type":"string"}
                        },
                        "required":["param1"]
        },
        " type2 " : {
            " type " : " object ",
                         "properties": {
                                  "param2":{"type":"string"},
                                  "param3":{"type":"string"}
                        },
                         "required":["param2","param3"]
        }
    }
}


来源:https://stackoverflow.com/questions/26724896/is-xml-schema-xsalternative-equivalent-available-in-json-schema

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!