Json схема допускает переопределение полей в объектах в массиве - PullRequest
1 голос
/ 09 марта 2020

У меня есть json, который выглядит следующим образом

  "List": {
     {"Color": "red"},
     {}
  },
  "Color": "grey"
}

, тогда как по умолчанию это серый цвет, и объект в списке может переопределить этот цвет. Схема должна позволять json проходить до тех пор, пока присутствует цвет по умолчанию (свойство на том же уровне List). В противном случае он должен только json пройти проверку схемы, если для всех элементов в списке указан «Цвет».

Могу ли я узнать, как я могу написать схему json, которая делает это чек об оплате? Мне известно о anyOf, но я не думаю, что он может проверять все элементы в массиве.

Я пробовал

{
  "type": "object",
  "properties": {
    "List": {"type": "array", "items": {"$ref:" "#/definitions/Item"}},
    "Color": {"type": "string"}
  },
  "definitions": {
    "Item": {"type: "object", "properties": " {"Color": {"type": "string"}}}
  },
  "anyOf": {
  {
    "type": "object",
      "required": ["Color"]  
  },
  {
    "type": "object",
    "List": {
      "type": "array",
      "items": {"$ref": "#/definitions/Item", "required": ["Color"]}
    }
  }
}

Но не похоже, что требуется цвет для anyOf [1] подбирается валидатором. Пожалуйста помоги.! Спасибо.

Ответы [ 2 ]

1 голос
/ 11 марта 2020

Схема в другом ответе верна, но излишне сложна. Вот пример, который удаляет дублирование и облегчает чтение схемы.

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "List": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "Color": { "type": "string" },
          "Shape": { "type": "string" }
        }
      }  
    },
    "Color": { "type": "string" },
    "Shape": { "type": "string" }
  },
  "required": ["List"],
  "allOf": [
    { "$ref": "#/definitions/color-required-if-no-default-color" },
    { "$ref": "#/definitions/shape-required-if-no-default-shape" }
  ],
  "definitions": {
    "color-required-if-no-default-color": {
      "anyOf": [
        { "required": ["Color"] },
        {
          "properties": {
            "List": {
              "items": { "required": ["Color"] }
            }
          }
        }
      ]
    },
    "shape-required-if-no-default-shape": {
      "anyOf": [
        { "required": ["Shape"] },
        {
          "properties": {
            "List": {
              "items": { "required": ["Shape"] }
            }
          }
        }
      ]
    }
  }
}
0 голосов
/ 09 марта 2020

Мне кажется, я нашел способ:

Схема похожа на ниже

{

    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "properties": {"Color": {"type":"string"}, "Shape": {"type": "string"}},
    "allOf":[
      {
      "anyOf": [
      {
      "required": ["Color"],
      "properties": {"List": {"type": "array", "items": {"$ref": "#/definitions/Item"}}}
      },
      {
       "properties": {"List": {"type": "array", "items": {"$ref": "#/definitions/ColorItem"}}}
      }
      ]
      },
      {
      "anyOf": [
      {
      "required": ["Shape"],
      "properties": {"List": {"type": "array", "items": {"$ref": "#/definitions/Item"}}}
      },
      {
       "properties": {"List": {"type": "array", "items": {"$ref": "#/definitions/ShapeItem"}}}
      }
      ]
      }
    ],
   "required": ["List"],
   "definitions": {
   "Item": {
       "type": "object",
        "properties": {}
      },
   "ColorItem": {
       "allOf": [{"$ref": "#/definitions/Item"},
                 {"properties": {"Color": {"type": "string"}}, "required": ["Color"]}] 
   },
     "ShapeItem": {
       "allOf": [{"$ref": "#/definitions/Item"},
                 {"properties": {"Shape": {"type": "string"}}, "required": ["Shape"]}] 
   }
  }
}

В основном это то, что я хочу. Таким образом, он будет проходить json только в том случае, если либо есть цвет / форма, считанные с верхнего уровня json, либо мы можем найти его в массиве.

...