我的 JSON 字符串将被格式化为:
{
"count":3,
"data":[
{
"a":{"ax":1}
},
{
"b":{"bx":2}
},
{
"c":{"cx":4}
}
]
}
data
数组包含许多 a
和 b
和 c
。并且没有其他种类的物体。
如果count==0
,data
应该是一个空数组[]
。
我正在使用 https://github.com/hoxworth/json-schema在 Ruby 中验证此类 JSON 对象。
require 'rubygems'
require 'json-schema'
p JSON::Validator.fully_validate('schema.json',"test.json")
schema.json
是:
{
"type":"object",
"$schema": "http://json-schema.org/draft-03/schema",
"required":true,
"properties":{
"count": { "type":"number", "id": "count", "required":true },
"data": { "type":"array", "id": "data", "required":true,
"items":[
{ "type":"object", "required":false, "properties":{ "a": { "type":"object", "id": "a", "required":true, "properties":{ "ax": { "type":"number", "id": "ax", "required":true } } } } },
{ "type":"object", "required":false, "properties":{ "b": { "type":"object", "id": "b", "required":true, "properties":{ "bx": { "type":"number", "id": "bx", "required":true } } } } },
{ "type":"object", "required":false, "properties":{ "c": { "type":"object", "id": "c", "required":true, "properties":{ "cx": { "type":"number", "id": "cx", "required":true } } } } }
]
}
}
}
但这对于 test.json
将通过验证,而我认为它应该失败:
{
"count":3,
"data":[
{
"a":{"ax":1}
},
{
"b":{"bx":2}
},
{
"c":{"cx":2}
},
{
"c": {"z":"aa"}
}
]
}
这 test.json
将失败,而我认为它应该通过:
{
"count":3,
"data":[
{
"a":{"ax":1}
},
{
"b":{"bx":2}
}
]
}
似乎错误的架构正在验证 data
数组是否包含 a,b,c
一次。
正确的架构应该是什么?
最佳答案
来自 JSON schema spec ,第 5.5 节。项目:
When this attribute value is an array of schemas and the instance
value is an array, each position in the instance array MUST conform
to the schema in the corresponding position for this array. This
called tuple typing.
您的架构定义要求数组的前三个元素恰好是“a”、“b”和“c”元素。如果 items
为空,则允许任何数组元素。同样,如果 additionalItems
为空,则允许任何其他数组元素。
要获得您想要的,您需要指定 "additionalItems": false
并且对于 items
,我认为以下(从您的定义中有所缩短)应该可以工作:
"items": {
"type": [
{"type":"object", "properties": {"a": {"type": "object", "properties": {"ax": { "type":"number"}}}}},
{"type":"object", "properties": {"b": {"type": "object", "properties": {"bx": { "type":"number"}}}}},
{"type":"object", "properties": {"c": {"type": "object", "properties": {"cx": { "type":"number"}}}}}
]
}
关于ruby - 如何为对象数组编写 JSON 模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10809459/