JSON架构的if / then需要嵌套对象

问题描述 投票:0回答:1

我有一个JSON:

{
    "i0": {
        "j0": {
            "a0": true
        }
    },
    "i1": {
        "j1": {
            "a1": "stuff"
        }
    }
}

我想验证:如果a0是真的,a1应符合规定。

我的模式是目前:

{
    "$schema": "http://json-schema.org/draft-07/schema",
    "id": "id",
    "type": "object",
    "required": [
        "i0",
        "i1"
    ],
    "allOf": [
        {
            "if": {
                "properties": {
                    "i0": {
                        "j0": {
                            "a0": true
                        }
                    }
                }
            },
            "then": {
                "properties": {
                    "i1": {
                        "j1": {
                            "required": [
                                "a1"
                            ]
                        }
                    }
                }
            }
        }
    ]
}

这条件似乎不实际运行。另外,我已经看到了得到了非常相似的条件,如果我尝试把required在同一水平上,因为我检查值继续工作。如:

"allOf": [
    {
        "if": {
            "a0": true
        },
        "then": {
            "required": [
                "a1"
            ]
        }
    }
]

但是这需要a1要承受j0a1一起。如何需要根据下j1值下j0对象?

json jsonschema json-schema-validator
1个回答
2
投票

尝试这个:

{
  "if":{
    "type":"object",
    "properties":{
      "i0":{
        "type":"object",
        "properties":{
          "j0":{
            "type":"object",
            "required":["a0"]
          }
        },
        "required":["j0"]
      }
    },
    "required":["i0"]
  },
  "then":{
    "type":"object",
    "properties":{
      "i1":{
        "type":"object",
        "properties":{
          "j1":{
            "type":"object",
            "required":["a1"]
          }
        },
        "required":["j1"]
      }
    },
    "required":["i1"]
  }
}

你必须使用if / then关键字内的整体结构,开始与他们有什么共同的根。在这种情况下,它们的路径开始在i0 / i1财产发散,所以你必须包括该点的整个结构。

type关键字确保你有一个对象,否则当其他类型,如strings或booleans,使用该模式可以通过验证。

required关键字确保if / then子模式只匹配在其实际包含i0.j0.a0 / i1.j1.a1财产路径,分别为对象。

另外,对于required /`A1性能a0关键字只能指定它们的存在。如果你需要它,你可以添加更多的验证到的子模式。

© www.soinside.com 2019 - 2024. All rights reserved.