JSON模式 - 如何定义依赖于文件中其他位置的值的类型

时间:2017-11-23 14:36:43

标签: json jsonschema

鉴于我有一个类似这样的JSON文件:



{
  "organisation":"Acme Co. Ltd",
  "organisation_abbreviation":"acme",
  "document_types":["invoice","credit-note"],
  "invoice":{
    "date":"2017-05-31",
    "value":238.44,
    "description":"invoice for xxx"
  },
  "credit_note":{
    "date":"2017-05-22",
    "value":0.0,
    "description":"DNOTE for xxx"
  },
}




显而易见的是,在文档类型中,我定义了各种允许的文档类型,然后在下面我将为这里命名的每种文档类型创建一个部分。

如何编写架构验证,以检查每个文档类型部分是否为上述类型之一(示例将失败,因为' credit-note'!=' credit_note&# 39)

1 个答案:

答案 0 :(得分:0)

使用OneOf填充您需要的内容:

{
      "$schema": "http://json-schema.org/draft-04/schema#",

      "title": "Acme billing",
      "type" : "object",
      "definitions": {
        "Entry": {
          "type": "object",
          "properties": {
             "date": "string",
             "value": "number",
             "description": "string"
          }
        }
      },
      "properties": {
        "organisation": "string",
        "organisation_abbreviation": "string",
        "document_types": {
          "enum": ["invoice","credit-note"]
        }
        "oneOf" : [{
          "properties": {
            "invoice": {
              "$ref" : "#/definitions/Entry"
            },
            "credit-note":{
              "$ref" : "#/definitions/Entry"
            }
          ]
       },
       "additionalProperties":false
     }
   }

}