Is it valid json (schema) to say that an element can be a single item or an array

浪尽此生 提交于 2021-01-28 06:22:01

问题


Is it possible to specify that a particular json value can be either a single element or an array?

E.g. Can both of following json documents be valid according to a given single json schema.

"person": {
    "name": "john",
    "friends": "jack"
}

"person": {
    "name": "john",
    "friends": ["jack", "jill"]
}

It's certainly possible (I believe) if you ignore the concept of schema, and simply when you are parsing using a parser such as rapidjson, to simply check if the element is an array or not before reading the contents.

What I want to know is, if I take this approach, will it be a problem if I want to specify a json schema for it later on?


回答1:


In JSON schema you can specify either one type that an item must match, or an array of types of which the item must match at least one (plus a few other possibilities).

So yes, you can have a schema that says the "friends" value is either a string, or an array of strings.

Obviously this means that client code and server code need to distinguish both cases and have different code for each case; you might consider sending an array with one string instead of someone has exactly one friend to simplify all code.




回答2:


Yes, JSON Schema can express this using the anyOf or oneOf keywords. These keywords specify an array of schemas. anyOf is valid if one or more of the schemas are valid. oneOf is valid if one and only one of the schemas is valid. anyOf is almost always sufficient.

Here is a JSON Schema that would validate your example person object

{
  "type": "object",
  "properties": {
    "name": { "type": "string" }
    "friends": {
      "anyOf": [
        { "$ref": "#/definitions/friend" },
        {
          "type": "array",
          "items": { "$ref": "#/definitions/friend" }
        }
      ]
    }
  },
  "definitions": {
    "friend": { "type": "string" }
  }
}


来源:https://stackoverflow.com/questions/34632245/is-it-valid-json-schema-to-say-that-an-element-can-be-a-single-item-or-an-arra

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