JSON SCHEMA - 如何检查数组中是否存在值

Jay*_*Jay 1 jsonschema

我有一个简单的问题。我有一个属性groupBy,它是一个数组,只包含两个可能的值“产品”和“日期”。现在我想再拍物业需要基于值存在GROUPBY阵列。在这种情况下,当我的groupBy数组包含“日期”时,我想进行解析!我怎样才能做到这一点 ?

谁可以检查数组是否包含值?

var data = {
    "pcsStreamId": 123123,
    "start": moment().valueOf(),
    "end": moment().valueOf(),
    "groupBy" : ["product"]
};

var schema = {
        "type": "object",
        "properties": {
            "pcsStreamId": { "type": "number" },
            "start": { "type": "integer", "minimum" : 0 },
            "end": { "type": "integer", "minimum" : 0 },
            "groupBy": {
                "type": "array",
                "uniqueItems": true,
                "items" : {
                    "type": "string",
                    "enum": ["product", "date"]
                },
               "oneOf": [
                   {
                       "contains": { "enum": ["date"] },
                       "required": ["resolution"]
                   }
                ]
            },
            "resolution" : {
                "type": "string",
                "enum": ["day", "year", "month", "shift"]
            },
        },
        "required": ["pcsStreamId", "start", "end", "groupBy"]

};
Run Code Online (Sandbox Code Playgroud)

Jas*_*ers 5

为了解决这个问题,我们必须使用一个叫做蕴涵的布尔逻辑概念。将要求置于布尔逻辑术语中,我们会说“groupBy”包含“日期”意味着需要“分辨率”。含义可以表示为“(不是A)或B”。换句话说,要么“groupBy”不包含“date”,要么需要“resolution”。在这种形式下,应该更清楚如何实施解决方案。

{
  "type": "object",
  "properties": {
    "pcsStreamId": { "type": "number" },
    "start": { "type": "integer", "minimum": 0 },
    "end": { "type": "integer", "minimum": 0 },
    "groupBy": {
      "type": "array",
      "uniqueItems": true,
      "items": { "enum": ["product", "date"] }
    },
    "resolution": { "enum": ["day", "year", "month", "shift"] }
  },
  "required": ["pcsStreamId", "start", "end", "groupBy"],
  "anyOf": [
    { "not": { "$ref": "#/definitions/contains-date" } },
    { "required": ["resolution"] }
  ],
  "definitions": {
    "contains-date": {
      "properties": {
        "groupBy": {
          "contains": { "enum": ["date"] }
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑

此答案使用新的 Draft-06contains关键字。我使用它是因为提问者使用了它,但是如果您使用的是草案 04,则可以改用“包含日期”的这个定义。它使用另一个逻辑标识(?x A <=> ¬?x ¬A)来获取contains关键字的功能。

{
  "definitions": {
    "contains-date": {
      "properties": {
        "groupBy": {
          "not": {
            "items": {
              "not": { "enum": ["date"] }
            }
          }
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)