How to specify which oneOf item a JSON object should take?

此生再无相见时 提交于 2019-12-02 05:51:12

Let's isolate the part of the schema that is failing.

{
  "type": "object",
  "properties": {
    "ObjA": {
      "type": "object",
      "properties": {
        "items": {
          "a": [90, 95],
          "b": [4, 8],
          "c": [0.2, 0.6]
        }
      },
      "additionalProperties": false
    }
  },
  "additionalProperties": false
}

Which is valiating this part of you test data

"ObjA"

The error you are seeing is telling you that the test data is a string, but the schema requires that it be an object.

Test data that matches your schema would look something like this

{
  "ObjA": {
    "items": ???
  }
}

I use ??? here because the value here can be any value that is valid JSON. The reason is because this schema does not contain any JSON Schema keywords.

{
  "a": [90, 95],
  "b": [4, 8],
  "c": [0.2, 0.6]
}

Therefore, there are no constraints on what value it can be. The warning messages you are seeing are telling you that a, b and c are not keywords.

I don't know what you are trying to express with this schema, but it's a far cry from the simple string in your test data.

Edit in response to comments

It sounds like you are trying to use JSON Schema for something it isn't designed for. The schema should describe only what the user needs to be concerned about. You will have to map the user values to hard coded structure in another step. In any case, it sounds like what you need is enum rather than oneOf.

{
  "enum": ["ObjA", "ObjB", "ObjC", "ObjD"]
}

or

{
  "enum": [
    {
      "a": [90, 95],
      "b": [4, 8],
      "c": [0.2, 0.6]
    },
    {
      "a": [100],
      "b": [0],
      "c": [0]
    },
    ...
  ]
}

There is no way to have both. If you really need to express that in your schema, I would add a custom keyword that shows the mapping. A validator will ignore it (and you might get a warning), but the relationship will be expressed for human readers and perhaps custom tools. It might look something like this

{
  "enum": ["ObjA", "ObjB", "ObjC", "ObjD"]
  "enumValues": {
    "ObjA": {
      "a": [90, 95],
      "b": [4, 8],
      "c": [0.2, 0.6]
    },
    "ObjB": {
      "a": [100],
      "b": [0],
      "c": [0]
    },
    ...
  ]
}

The enum tells the user what values are allowed and the validator can check this. Then the enumValues keyword is something we made up to express the relationship between the enum values and their actual values.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!