我有从GraphQL传回来的数据,我想在操作这些数据之前,用JSON模式来验证这些数据。
在graphQL中可能有比我目前更好的方法,但传回来的数据可以是两种属性相同的类型。
比如简化版的数据...
obj: {
audio: {
artists: []
},
video: {}
}
或
obj: {
audio: {},
video: {
artists: []
}
}
所以有效性将是。
audio
和 video
财产audio
作为一个对象,其属性为 artists
和一个空属性 video
对象 video
作为一个对象,其属性为 artists
和一个空属性 audio
对象audio
或 video
一齐空audio
或 video
应有尽有我已经建立了一个简化的模式,看起来像这样。
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "file://schemas/simple.schema.json",
"title": "simplified data",
"description": "simple",
"type": "object",
"properties": {
"audio": {
"type": "object"
},
"video": {
"type": "object"
}
},
"oneOf": [
{
"audio": {
"type": "object",
"properties": {
"artists": {
"type": "array"
}
}
},
"video": {
"type": "object",
"properties": {}
}
},
{
"audio": {
"type": "object",
"properties": {}
},
"video": {
"type": "object",
"properties": {
"artists": {
"type": "array"
}
}
}
}
]
}
但AJV在运行时似乎不能正确地验证数据。
{
"audio": {
"artists": []
},
"video": {}
}
我的模式可能有什么问题?
经过最初的尝试,Jason指出了一个更简单的解决方案... ...
使用 oneOf
你可以指定只有一个对象可以有至少一个属性。
你可以在这里进行测试。https:/jsonschema.devsSSRaL
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "file://schemas/simple.schema.json",
"properties": {
"audio": {
"type": [
"object"
],
"properties": {
"artists": {
"$comment": "whatever validation you want"
}
}
},
"video": {
"type": [
"object"
],
"properties": {
"artists": {
"$comment": "whatever validation you want"
}
}
}
},
"oneOf": [
{
"properties": {
"video": {
"minProperties": 1
}
}
},
{
"properties": {
"audio": {
"minProperties": 1
}
}
}
]
}