【问题标题】:JSON schema: Enforce array conent by optionsJSON 模式:通过选项强制执行数组内容
【发布时间】:2021-06-28 13:30:17
【问题描述】:

我有一个 JSON 数组,我想强制执行它的内容。

假设我有四种对象类型A, BCD。我的数组可能包含来自A, B, Cstring 类型的任意数量的项目。但不允许使用D 或其他类型。

  • [A, B, C, A, A, B, "stuff", "morestuff", C] 有效
  • [A, A, 3, C] 无效(包含数字 3)
  • [A, D, A, B] 无效(包含 D)

阅读spec 看起来好像这是不可能的。只有元组验证和列表验证。 但是,对于元组验证 a) 顺序很重要 b) 不能有任意数量的相同类型的对象。列表验证失败,因为存在不同类型的对象。

这真的不可能吗?

【问题讨论】:

    标签: arrays json schema


    【解决方案1】:

    是的,可以使用类型数组作为项目的类型:

    {
      "type": "array",
      "items": {
        "type": [A, B, C, "string"]
      }
    }
    

    参考:

    数组的项目类型: https://json-schema.org/understanding-json-schema/reference/array.html#list-validation

    一个类型有多个选项: http://json-schema.org/understanding-json-schema/reference/type.html

    【讨论】:

    • 谢谢!应该更仔细地阅读文档。
    猜你喜欢
    • 2013-11-10
    • 1970-01-01
    • 2013-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多