首页 > 解决方案 > JsonSchema 如何对数组使用只读

问题描述

我阅读了规范。但是,我没有找到任何关于如何使用readOnlyArray 的信息。并且单个readonly属性不足以涵盖不同的场景。

一个示例数组模式,如下所示:

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "$id": "http://example.com/product.schema.json",
    "title": "Products",
    "type": "array",
    "items": {
        "type": "object",
        "properties": {
            "productId": {
                "description": "The unique identifier for a product",
                "type": "integer"
            },
            "productName": {
                "description": "Name of the product",
                "type": "string"
            },
            "price": {
                "description": "The price of the product",
                "type": "number"
            }
        }
    }
}

是否有可能实现以下目标?

  1. 数组不允许添加/删除数组的任何项。但是,允许更新数组的任何项目。
  2. 数组不允许更新数组的任何项。但是,允许添加/删除数组的项目。一旦一个项目被添加到数组中,我唯一能做的就是“删除”。

标签: arraysjsonschemajson-schema-validator

解决方案


readOnly描述这些限制的工具太生硬了。但是,只需稍作改动,您就可以使用 JSON Hyper-Schema 来表达它。您必须分别对单个产品和产品列表进行建模。不像readOnly说你不能做的,links说你能做的。以下是您确定的每个案例的情况。

  1. 数组不允许添加/删除数组的任何项。但是,允许更新数组的任何项目。
{
  "$schema": "http://json-schema.org/draft-07/hyper-schema#",
  "$id": "http://example.com/product-list.schema.json",
  "type": "array",
  "items": { "$ref": "product.schema.json" }
}
{
  "$schema": "http://json-schema.org/draft-07/hyper-schema#",
  "$id": "http://example.com/product.schema.json",
  "type": "object",
  "properties": {
    "productId": { "type": "integer" },
    "productName": { "type": "string" },
    "price": { "type": "number" }
  },
  "links": [
    { "rel": "edit", "href": "/product/{productId}" }
  ]
}
  1. 数组不允许更新数组的任何项。但是,允许添加/删除数组的项目。一旦一个项目被添加到数组中,我唯一能做的就是“删除”。
{
  "$schema": "http://json-schema.org/draft-07/hyper-schema#",
  "$id": "http://example.com/product-list.schema.json",
  "type": "array",
  "items": { "$ref": "product.schema.json" },
  "links": [
    {
      "rel": "create",
      "href": "/products",
      "schema": { "$ref": "product-create.schema.json" }
    }
  ]
}
{
  "$schema": "http://json-schema.org/draft-07/hyper-schema#",
  "$id": "http://example.com/product.schema.json",
  "type": "object",
  "properties": {
    "productId": { "type": "integer" },
    "productName": { "type": "string" },
    "price": { "type": "number" }
  },
  "links": [
    { "rel": "delete", "href": "/product/{productId}" }
  ]
}

推荐阅读