JSON 架构:通过选项强制执行数组内容
JSON schema: Enforce array conent by options
我有一个 JSON 数组,我想强制执行它的内容。
假设我有四种对象类型 A, B
、C
和 D
。我的数组可能包含来自 A, B, C
或 string
类型的任意数量的项目。 D
或其他类型是不允许的。
即
[A, B, C, A, A, B, "stuff", "morestuff", C]
有效
[A, A, 3, C]
无效(包含数字 3)
[A, D, A, B]
无效(包含 D)
阅读 spec 似乎这是不可能的。只有元组验证和列表验证。
但是对于元组验证 a) 顺序很重要 b) 不能有任意数量的相同类型的对象。列表验证失败,因为存在不同类型的对象。
这真的不可能吗?
是的,可以使用类型数组作为项目的类型:
{
"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
我有一个 JSON 数组,我想强制执行它的内容。
假设我有四种对象类型 A, B
、C
和 D
。我的数组可能包含来自 A, B, C
或 string
类型的任意数量的项目。 D
或其他类型是不允许的。
即
[A, B, C, A, A, B, "stuff", "morestuff", C]
有效[A, A, 3, C]
无效(包含数字 3)[A, D, A, B]
无效(包含 D)
阅读 spec 似乎这是不可能的。只有元组验证和列表验证。 但是对于元组验证 a) 顺序很重要 b) 不能有任意数量的相同类型的对象。列表验证失败,因为存在不同类型的对象。
这真的不可能吗?
是的,可以使用类型数组作为项目的类型:
{
"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