I'd like to create a JSON schema that restricts one property's values based on another property's values.
An example valid object might look like this:
{
"lookup": {
"foo": "string",
"bar": "number",
},
// properties in `values` must exist in `lookup`
"values": {
// `foo` must be a string
"foo": "string is OK",
// `bar` must be a number
"bar": 100
}
}
The idea is for the schema to enforce a relationship between the two properties.
{
"type": "object",
"properties": {
"lookup" : {
"type": "object",
"additionalProperties" : {
"type": "string",
"enum": ["string", "number"]
}
},
"values": {
"type": "object",
// - this value's properties must exist in `lookup`
// - if the property in `lookup` is set to `string`, the type here must be `string`; if the property in `lookup` is set to `number`, the type here must be `number`
}
}
}
This is possible in some cases. While you can't restrict a piece of data to certain values taken from other parts of the data (for example: using property X to provide a list of values that property Y can have), you can specify conditionals between parts of your schema.
requirement 1: this value's properties must exist in lookup -> not possible
requirement 2: if the property in lookup is set to string, the type here must be string; if the property in lookup is set to number, the type here must be number -> possible
See https://json-schema.org/understanding-json-schema/reference/conditionals.html for the various options available to you.
This is not possible with the standard specification of JSON Schema.
Related
I noticed the following: Reusable enum types in json schema , which talks about defining a reusable enum type in JSON schema.
I would have assumed USING this reusable enum type would be trivial, simply specifying (in this case) the value of "MyEnum" for a "type" value.
I don't know if the results from Oxygen XML are authoritative, but I tried something like the following:
{
"$schema": "https://json-schema.org/draft/2019-09/schema#",
"type": "object",
"properties": {
"content": {"$ref": "#/definitions/content_type"}
},
"additionalProperties": false,
"definitions": {
"costCategory_type": {
"type": "object",
"enum": ["VH", "H", "M", "L"]
},
"allowedDevices_type": {
"type": "object",
"properties": {
"costCategory": {
"type": "costCategory_type"
},
On the line near the bottom of this, where I reference "costCategory_type", Oxygen gives me a syntax error, saying
#/definitions/allowedDevices_type/properties/costCategory/type: unknown type: [costCategory_type]
What am I missing?
Yes, the type keyword can only have values from the list null, boolean, object, array, string, number, integer. You can reference definitions with the $ref keyword:
...
"properties": {
"costCategory": {
"$ref": "#/definitions/costCategory_type",
}
}
(incidentally, your definition won't ever evaluate successfully as-is since you define it as being the "object" type, but the list of values in the enum are all strings.)
I've been using the readOnly keyword in my schemas and I just realized that I was just making up my own semantics. Now I'm cleaning up a bunch of my designs and trying to validate that I was using this annotation as it was intended. The validation spec is what I'm basing this question on but I'd like to be aware of more example usage scenarios.
Let me give three examples. In this first example I mean to say the entire resource is read only. Nothing can be mutated at any level.
{
"type": "object",
"readOnly": true,
"properties": {
"name": {
"type": "string",
},
"members": {
"type": "object",
"properties": {
"member1": { "type" : "string" },
"member2": { "type" : "string" }
}
}
}
}
I don't think that's too controversial. But originally, my own mental model was that readOnly at the top level meant you couldn't replace this resource with a new resource. The server would prevent that. But the internal members were still mutable. So I sprinkled readOnly at the name sub-schema and each member sub-schema. I think removing all of those was correct. (My mental model was maybe loosely based on how I interpret const variables in JavaScript. If my const var is an object, I can't change the value of the variable, but I can mutate its members or even add members to it.)
In the second example I leave readOnly out of the schema completely. So it's not too controversial to take that to mean anything is mutable in the resource.
{
"type": "object",
"properties": {
"name": {
"type": "string",
},
"members": {
"type": "object",
"properties": {
"member1": { "type" : "string" },
"member2": { "type" : "string" }
}
}
}
}
In the third example, I want to mix and match
{
"type": "object",
"properties": {
"name": {
"type": "string",
"readOnly": true
},
"members": {
"type": "object",
"properties": {
"member1": { "type" : "string", "readOnly": true },
"member2": { "type" : "string", "readOnly": true },
"member3": { "type" : "string"},
"member4": { "type" : "string"}
}
}
}
}
In this example the name, member1 and member2 are immutable. member3 and member4 can be modified.
So the question is, is there anything wrong about my interpretation of readOnly?
The spec, as you linked defines the following for readOnly...
If "readOnly" has a value of boolean true, it indicates that the value
of the instance is managed exclusively by the owning authority, and
attempts by an application to modify the value of this property are
expected to be ignored or rejected by that owning authority.
https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-02#section-9.4
If you take the JSON defined meaning of value, it's the bit to the right of the key followed by colon. Therefore I would read this as any part of the value.
The OpenAPI specification only really defines readOnly as being applicable to individual properties.
In a JSON Schema is is valid to have a $ref and then other properties within the same schema, for example.
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"title": "My schema",
"properties": {
"scripts": {
"$ref": "#/definitions/scriptsBase",
"description": "More docs.",
"minLength": 10
}
},
"definitions": {
"scriptsBase": {
"type": "string",
"description": "Base Description",
"minLength": 5
}
}
}
If this is allowable, then what are the rules when it comes to resolving properties defined in the $refed and the $refing schemas (in this example minLength and description. But potentially this could become much more complex if allOf etc where defined in both.
Found the answer in json schema property description and "$ref" usage, basically if a $ref exists all other properties are ignored.
https://datatracker.ietf.org/doc/html/draft-pbryan-zyp-json-ref-03#section-3
Syntax
A JSON Reference is a JSON object, which contains a member named
"$ref", which has a JSON string value. Example:
{ "$ref": "http://example.com/example.json#/foo/bar" }
If a JSON value does not have these characteristics, then it SHOULD
NOT be interpreted as a JSON Reference.
The "$ref" string value contains a URI [RFC3986], which identifies
the location of the JSON value being referenced. It is an error
condition if the string value does not conform to URI syntax rules.
Any members other than "$ref" in a JSON Reference object SHALL be
ignored.
Are there any differences between the following two JSON schemas validations or do they validate the same data structure?
SomeProperty
{
"type": ["integer","string"]
}
SomeProperty
{
"anyOf": [
{
"type": "integer"
},
{
"type": "string"
}
]
}
They are equivalent!
type
The value of this keyword MUST be either a string or an array. If it
is an array, elements of the array MUST be strings and MUST be unique.
String values MUST be one of the six primitive types ("null",
"boolean", "object", "array", "number", or "string"), or "integer"
which matches any number with a zero fractional part.
An instance validates if and only if the instance is in any of the
sets listed for this keyword.
https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-01#section-6.1.1
Notice the last section "...in any of..."
Given this example JSON:
{
"type": "number",
"values": [ 34, 42, 99 ]
}
Is it possible to define JSON Schema that makes sure that the contents of
the values array are of the type specified in another property (in this example type)?
Above type is saying that the array values can only contain integers (using the specifier "number").
Or specify that values contains strings:
{
"type": "string",
"values": [ "hello", "world" ]
}
Yes you can use the "items" keyword. If it has a single value then that value is the schema for every element of the array.
{
"type": "array",
"items": { "type: "string" }
}
Assuming you're using a draft4 schema like most people do, section 8.2.3.1 of the specification states:
8.2.3.1. If "items" is a schema
If items is a schema, then the child instance must be valid against
this schema, regardless of its index, and regardless of the value of
"additionalItems".
Yes, but you will have to write an if/then block for each type you want to support.
The Understanding JSON Schema has a section on if/then/else: http://json-schema.org/understanding-json-schema/reference/conditionals.html
Here is an extract that explains how if/then/else works.
For example, let’s say you wanted to write a schema to handle
addresses in the United States and Canada. These countries have
different postal code formats, and we want to select which format to
validate against based on the country. If the address is in the United
States, the postal_code field is a “zipcode”: five numeric digits
followed by an optional four digit suffix. If the address is in
Canada, the postal_code field is a six digit alphanumeric string where
letters and numbers alternate.
{
"type": "object",
"properties": {
"street_address": {
"type": "string"
},
"country": {
"enum": ["United States of America", "Canada"]
}
},
"if": {
"properties": { "country": { "const": "United States of America" } }
},
"then": {
"properties": { "postal_code": { "pattern": "[0-9]{5}(-[0-9]{4})?" } }
},
"else": {
"properties": { "postal_code": { "pattern": "[A-Z][0-9][A-Z] [0-9][A-Z][0-9]" } }
}
}
For each type you want to support, you would need to write if/then object, and wrap all of them in an allOf.