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

JSON SCHEMA - How can i check a values exists in an array

我有一个简单的问题。我有一个 属性 groupBy,它是一个数组,只包含两个可能的值 "product" 和 "date"。现在我想根据 value existsgroupBy 数组中创建另一个 属性。在这种情况下,当我的 groupBy 数组包含 "date" 时,我想进行解析!我该怎么做?

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

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"]

};

您的 groupby 属性 似乎是一个对象。可能是您正在谈论的嵌套枚举 属性(因为它是一个数组并包含日期和产品)。但是,一旦您将此 json 解析为一个对象,您就可以检查如下内容:

groupby.items.enums.indexOf('date') === -1

array.indexOf(anyItem) returns 项目的索引,如果存在于数组中,否则它 returns -1.

希望对您有所帮助

要解决这个问题,我们必须使用一个称为蕴涵的布尔逻辑概念。用布尔逻辑术语来表示要求,我们会说 "groupBy" 包含 "date" 暗示 需要 "resolution"。蕴涵可以表示为“(非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"] }
        }
      }
    }
  }
}

编辑

此答案使用新的 draft-06 contains 关键字。我使用它是因为提问者使用了它,但是如果你在 draft-04 上,你可以使用 "contains-date" 的这个定义来代替。它使用另一个逻辑标识(∃x A <=> ¬∀x ¬A)来获得contains关键字的功能。

{
  "definitions": {
    "contains-date": {
      "properties": {
        "groupBy": {
          "not": {
            "items": {
              "not": { "enum": ["date"] }
            }
          }
        }
      }
    }
  }
}