【问题标题】:JSON Schema 中基于 $ref 枚举的对象属性
【发布时间】:2022-01-23 07:56:10
【问题描述】:

我已经看过了:


我需要我的 JSON 模式来强制一个对象具有枚举中的所有属性,我不知道如何。

stuff.list.json

注意:想象一下,但要长得多。

{
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "$id": "https://example.com/product.schema.json",
    "title": "ListOfStuff",
    "description": "List of stuff",
    "enum": [
        "Thing1",
        "Thing2",
        "Thing3"
    ],
    "uniqueItems": true
}

stuff.schema.json

{
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "$id": "https://example.com/product.schema.json",
    "title": "Stuff Defined",
    "description": "Stuff in detail",
    "type": "object",
    "properties": {
        /* a property for each enum value of stuff.list.json  */: { <----- ???
            "type": "array",
            "items": { /* Schema for each item */ }
        }
    },
    "required": [ /* $ref: ./stuff.list.json ?? */ ]
 }

我希望它强制执行的输出是:

 {
     "Thing1": [],
     "Thing2": [],
     "Thing3": []
 }

【问题讨论】:

    标签: json jsonschema


    【解决方案1】:

    您在寻找required keyword 吗?您可以将其放在定义中并稍后引用:

    "$defs": {
      "required_properties": {
        "required": [
          "Thing1",
          "Thing2",
          "Thing3"
        ]
      }
    },
    ...
    

    然后在您的主架构中:

    {
      ...,
      "type": "object",
      "$ref": "stuff.list.json#/$defs/required_properties",
      ...,
    }
    

    【讨论】:

      猜你喜欢
      • 2020-10-07
      • 2018-04-18
      • 2022-12-17
      • 2020-07-19
      • 2017-03-05
      • 1970-01-01
      • 2020-11-04
      • 1970-01-01
      相关资源
      最近更新 更多