JSON -Schema добавить свойство к элементу условно - PullRequest
2 голосов
/ 19 февраля 2020

У меня есть следующие JSON данные

[
  {
    "type": "social_media_profiles",
    "data": {
      "profiles": [
        {
          "key": "twitter",
          "data": "username",
          "field": "handle",
          "label": "Tweet"
        },
        {
          "key": "customLink",
          "data": "abc",
          "field": "url",
          "label": "Click",
          "color": {
            "button": "red",
            "text": "green",
            "border": "yellow"
          }
        }
      ]
    }
  }
]

и следующая схема jsong

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "array",
  "additionalProperties": false,
  "items": {
    "type": "object",
    "required": ["type", "data"],
    "additionalProperties": false,
    "properties": {
      "type": {
        "type": "string",
        "enum": [
          "social_media_profiles"
        ]
      },
      "data": {
        "type": "object"
      }
    },
    "allOf": [
      {
        "if": {
          "properties": {
            "type": {
              "const": "social_media_profiles"
            }
          }
        },
        "then": {
          "properties": {
            "data": {
              "type": "object",
              "required": ["profiles"],
              "additionalProperties": false,
              "properties": {
                "profiles": {
                  "type": "array",
                  "items": {
                    "type": "object",
                    "required": ["data", "field", "key"],
                    "additionalProperties": false,
                    "properties": {
                      "data": {
                        "type": "string",
                        "description": "Data contains either profile url, handle id, etc."
                      },
                      "field": {
                        "type": "string",
                        "enum": ["url", "handle", "id", "tel"],
                        "description": "Type of field value."
                      },
                      "key": {
                        "type": "string",
                        "description": "Social media name used to distinguish each social network"
                      },
                      "label": {
                        "type": "string",
                        "description": "Label to display on the landing page"
                      }
                    },
                    "allOf": [
                      {
                        "if": {
                          "properties": {
                            "key": {
                              "const": "customLink"
                            }
                          }
                        },
                        "then": {
                          "properties": {
                            "color": {
                              "type": "object",
                              "additionalProperties": false,
                              "required": [],
                              "properties": {
                                "button": {
                                  "type": "string"
                                },
                                "text": {
                                  "type": "string"
                                },
                                "border": {
                                  "type": "string"
                                }
                              }
                            }
                          }
                        }
                      }
                    ]
                  }
                }
              }
            }
          }
        }
      }
    ]
  }
}

Я хочу добавить новое свойство color к элементу profiles на основе условие, когда key элемента равно customLink.

Если key не равно customLink, то свойства color не должно быть.

Проверка схемы из https://www.jsonschemavalidator.net/ выдает ошибку

 Found 2 error(s)

 Message: JSON does not match all schemas from 'allOf'. Invalid schema indexes: 0.
 Schema path: #/items/allOf

    Message: JSON does not match schema from 'then'.
    Schema path: #/items/allOf/0/then/then

Как я могу условно добавить новое свойство на основе значения свойства родного брата?

1 Ответ

0 голосов
/ 19 февраля 2020

В вашей profiles.items схеме вы определили additionalProperties: false.

additionalProperties, зависит от properties, определенного в том же объекте схемы, что означает, что color всегда будет запрещен.

Вы можете разделить свои опасения на «какие свойства разрешены» и «если их значения действительны».

Перемещение проверки для объекта color в profiles.properties позволяет поддерживать additionalProperties: false на уровне этого объекта.

Значения схемы объекта properties применяются только к расположению экземпляра для ключей, если они существуют (следовательно, необходимо использовать required, чтобы требовать указание c ключи ... требуются).

Упростив условный раздел, вы получите более чистую схему.

Теперь вам нужно только определить условие, при котором color требуется, не беспокоясь о том, как должно выглядеть значение.

Код Sudo: если key равно customLink, тогда требуется color, в противном случае не указывайте color.

{
  "if": {
    "properties": {
      "key": {
        "const": "customLink"
      }
    }
  },
  "then": {
    "required": [
      "color"
    ]
  },
  "else": {
    "not": {
      "required": [
        "color"
      ]
    }
  }
}

Используя not, вы можете инвертировать результат проверки прикладной подсхемы, это то, что вам нужно сделать, если вы хотите определить, что указанное свойство c НЕ разрешено.

Вот живая демонстрация, с которой можно поиграть: https://jsonschema.dev/s/C9V6N

А для процветания, вот полная схема с удалением одной или двух избыточностей.

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "array",
  "items": {
    "type": "object",
    "required": [
      "type",
      "data"
    ],
    "additionalProperties": false,
    "properties": {
      "type": {
        "type": "string",
        "enum": [
          "social_media_profiles"
        ]
      },
      "data": {
        "type": "object"
      }
    },
    "allOf": [
      {
        "properties": {
          "data": {
            "type": "object",
            "required": [
              "profiles"
            ],
            "additionalProperties": false,
            "properties": {
              "profiles": {
                "type": "array",
                "items": {
                  "type": "object",
                  "required": [
                    "data",
                    "field",
                    "key"
                  ],
                  "additionalProperties": false,
                  "properties": {
                    "data": {
                      "type": "string",
                      "description": "Data contains either profile url, handle id, etc."
                    },
                    "field": {
                      "type": "string",
                      "enum": [
                        "url",
                        "handle",
                        "id",
                        "tel"
                      ],
                      "description": "Type of field value."
                    },
                    "key": {
                      "type": "string",
                      "description": "Social media name used to distinguish each social network"
                    },
                    "label": {
                      "type": "string",
                      "description": "Label to display on the landing page"
                    },
                    "color": {
                      "type": "object",
                      "additionalProperties": false,
                      "properties": {
                        "button": {
                          "type": "string"
                        },
                        "text": {
                          "type": "string"
                        },
                        "border": {
                          "type": "string"
                        }
                      }
                    }
                  },
                  "allOf": [
                    {
                      "if": {
                        "properties": {
                          "key": {
                            "const": "customLink"
                          }
                        }
                      },
                      "then": {
                        "required": [
                          "color"
                        ]
                      },
                      "else": {
                        "not": {
                          "required": [
                            "color"
                          ]
                        }
                      }
                    }
                  ]
                }
              }
            }
          }
        }
      }
    ]
  }
}
...