Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON schema for object with either A and B or C required properties

Tags:

jsonschema

I have two possible JSON objects for one request:

{
  "from": "string",
  "to": "string",
  "text": "string"
}

or

{
  "number": "integer",
  "text": "string"
}

In both cases "text" property is optional. Other properties are required (either "number, or both "from" and "to").

What will be the correct JSON schema to validate this?

like image 990
Alexander Zhak Avatar asked Jul 05 '16 16:07

Alexander Zhak


People also ask

What is JSON Schema properties?

Properties. The properties (key-value pairs) on an object are defined using the properties keyword. The value of properties is an object, where each key is the name of a property and each value is a schema used to validate that property.

What is required in JSON Schema?

In JSON, the “keys” must always be strings. Each of these pairs is conventionally referred to as a “property”. In Python, "objects" are analogous to the dict type. An important difference, however, is that while Python dictionaries may use anything hashable as a key, in JSON all the keys must be strings.

What does Exclusiveminimum property in JSON Schema mean?

Gets or sets a flag indicating whether the value can not equal the number defined by the minimum attribute (Minimum).

What is JSON object schema?

JSON Schema is a grammar language for defining the structure, content, and (to some extent) semantics of JSON objects. It lets you specify metadata (data about data) about what an object's properties mean and what values are valid for those properties.


1 Answers

Here is another solution that I think is a bit more clear. The dependencies clause ensures that "from" and "to" always come as a pair. Then the oneOf clause can be really simple and avoid the not-required boilerplate.

{
  "type": "object",
  "properties": {
    "from": { "type": "string" },
    "to": { "type": "string" },
    "number": { "type": "integer" },
    "text": { "type": "string" }
  },
  "dependencies": {
    "from": ["to"],
    "to": ["from"]
  },
  "oneOf": [
    { "required": ["from"] },
    { "required": ["number"] }
  ]
}
like image 121
Jason Desrosiers Avatar answered Oct 24 '22 10:10

Jason Desrosiers