dee*_*ter 25 validation json jsonschema
我有一个无序的JSON项目数组.根据规范http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.5,下面的json模式将仅验证数组中的对象是否显示为IN THAT ORDER.我不想指定一个订单,只需验证数组中的对象,无论对象的顺序或数量如何.从规范我似乎无法理解这是如何做到的.
"transactions" : {
"type" : "array",
"items" : [
{
"type" : "object",
"properties" : {
"type" : {
"type" : "string",
"enum" : ["BUILD", "REASSIGN"]
}
}
},
{
"type" : "object",
"properties" : {
"type" : {
"type" : "string",
"enum" : ["BREAK"]
}
}
}
]
}
Run Code Online (Sandbox Code Playgroud)
dee*_*ter 46
我在JSON架构google组中问了同样的问题,并且很快得到了解答.用户fge要求我在这里发布他的回复:
你好,
目前的规范是草案v4,而不是草案v3.更具体地说,验证规范在这里:
http://tools.ietf.org/html/draft-fge-json-schema-validation-00
网站不是最新的,我不知道为什么......我会提交拉取请求.
使用草案v4,您可以使用:
{
"type": "array",
"items": {
"oneOf": [
{"first": [ "schema", "here" ] },
{"other": [ "schema": "here" ] }
]
}
}
Run Code Online (Sandbox Code Playgroud)
例如,这是一个数组的模式,其中的项可以是字符串或整数(虽然可以用更简单的方式编写):
{
"type": "array",
"items": {
"oneOf": [
{"type": "string"},
{"type": "integer"}
]
}
}
Run Code Online (Sandbox Code Playgroud)
这是正确的答案.我更正的架构现在包括:
"transactions" : {
"type" : "array",
"items" : {
"oneOf" : [
{
"type" : "object",
"properties" : {
"type" : {
"type" : "string",
"enum" : ["BUILD", "REASSIGN"]
}
}
},
{
"type" : "object",
"properties" : {
"type" : {
"type" : "string",
"enum" : ["BREAK"]
}
}
}
]
}
}
Run Code Online (Sandbox Code Playgroud)
小智 7
我也研究这个问题有一段时间了。但一直未能找到可行的解决方案。如果您只有一种模式,例如,它可以正常工作。
"transactions" : {
"type" : "array",
"items" :
{
"type" : "object",
"properties" : {
"type" : {
"type" : "string",
"enum" : ["BREAK"]
},
}
}
Run Code Online (Sandbox Code Playgroud)
然后你只需跳过数组括号,并使用一个对象。然而,如果你想做你正在做的事情,似乎没有可靠的答案。这是迄今为止我发现的唯一的东西:http://the-long-dark-tech-time.blogspot.se/2012/12/using-json-schema-with-array-of-mixed.html
对于任何坚持草案 3 模式的人。有一个“Type”关键字相当于草案 4 中的“anyOf”:
所以你可以使用
{
"fooBar" : {
"type" : "array",
"items" : {
"type" : [{
"type" : "object",
"properties" : {
"foo" : {
"type" : "string"
}
}
}, {
"type" : "object",
"properties" : {
"bar" : {
"type" : "string"
}
}
}
]
}
}
}
Run Code Online (Sandbox Code Playgroud)
作为对用户 Vdex 的回应:这不是等价的,您所写的意味着数组元素在数组中按此特定顺序出现。
如果您使用此模式验证器,则须遵守正确的实现。
有了这个架构:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "array",
"items": [
{
"type": "boolean"
},
{
"type": "number"
},
{
"type": "string"
}
]
}
Run Code Online (Sandbox Code Playgroud)
该 JSON 将被验证:
[
true,
5,
"a",
"6",
"a",
5.2
]
Run Code Online (Sandbox Code Playgroud)
但不是这个:
[
5,
true,
"a",
"6",
"a",
5.2
]
Run Code Online (Sandbox Code Playgroud)
因此,其目标与“oneOf”等关键字完全不同。