基于引用对象的值的条件JSON模式验证

huangapple go评论59阅读模式
英文:

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,我想进一步解释一下。例如,当所引用的sourcetypea时,我必须指定a-attribute并且不能指定b-attribute

当所引用的sourcetypeb时,我应该被强制指定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 ids in the source objects.

  1. How can I express this relationship in JSON Schema?
  2. How can I do conditional subschema application for the data objects based on the value of the type property of the referred sources 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.

huangapple
  • 本文由 发表于 2023年7月27日 17:21:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76778284.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定