英文:
Conditional JSON schema validation based on value of referenced object
问题
假设我有一个如下所示的JSON对象:
{
"sources": [
{
"id": "foo",
"type": "a"
},
{
"id": "bar",
"type": "b"
}
],
"data": [
{
"source-id": "foo",
"a-attribute": 10
},
{
"source-id": "bar",
"b-attribute": 20
}
]
}
在这里,data
对象中的source-id
必须等于source
对象中的一个id
。
1)我如何在JSON Schema中表示这种关系?
2)如何根据所引用的sources
对象的type
属性的值对data
对象进行条件子模式应用?
对于问题2,我想进一步解释一下。例如,当所引用的source
的type
为a
时,我必须指定a-attribute
并且不能指定b-attribute
。
当所引用的source
的type
为b
时,我应该被强制指定b-attribute
而不是a-attribute
。
这是否可以通过JSON Schema实现,还是我需要编写自定义验证代码?
英文:
Imagine I have a JSON object like the following:
{
"sources": [
{
"id": "foo",
"type": "a"
},
{
"id": "bar",
"type": "b"
}
],
"data": [
{
"source-id": "foo",
"a-attribute": 10
},
{
"source-id": "bar",
"b-attribute": 20
}
]
}
Here, the source-id
in the data
objects must be equal to one of the id
s in the source
objects.
- How can I express this relationship in JSON Schema?
- How can I do conditional subschema application for the
data
objects based on the value of thetype
property of the referredsources
object?
Expanding a bit on 2., I would like for example that when the type
of the referred source
is a
, then I have to specify a-attribute
and cannot specify b-attribute
.
And when the type
of the referred source is b
, then I should be forced to specify b-attribute
and not a-attribute
.
Can this be achieved with JSON Schema, or do I need to write custom validation code?
答案1
得分: 1
我在 JSON Schema Slack 上被告知,JSON Schema 无法表达关系完整性约束。
所以,我想要做的事情无法通过模式来实现,而需要进行单独的验证。
英文:
I was told in the JSON Schema Slack that JSON Schema today cannot express relational integrity constraints.
So what I would like to do is not achievable with a schema but requires separate validation.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论