JSON Schema with unknown property names
Solution 1
Use patternProperties
instead of properties
. In the example below, the pattern match regex .*
accepts any property name and I am allowing types of string
or null
only by using "additionalProperties": false
.
"patternProperties": {
"^.*$": {
"anyOf": [
{"type": "string"},
{"type": "null"}
]
}
},
"additionalProperties": false
... or if you just want to allow a string in your "object" (like in the original question):
"patternProperties": {
"^.*$": {
{"type": "string"},
}
},
"additionalProperties": false
Solution 2
You can make constraints on properties not explicitly defined. The following schema enforces "meta" to be an array of objects whose properties are of type string:
{
"properties" : {
"meta" : {
"type" : "array",
"items" : {
"type" : "object",
"additionalProperties" : {
"type" : "string"
}
}
}
}
}
In case you just want to have an array of strings, you may use the following schema:
{
"properties" : {
"meta" : {
"type" : "array",
"items" : {
"type" : "string"
}
}
}
}
Thami Bouchnafa
Motivation, performance and originality are the key to success. Computer science is much more than programming. A computer scientist hast to think logically and solve difficult problems. He has to manage projects and realize their objectives.
Updated on November 25, 2021Comments
-
Thami Bouchnafa over 2 years
I want to have a JSON Schema with unknown property names in an array of objects. A good example is the meta-data of a web page:
"meta": { "type": "array", "items": { "type": "object", "properties": { "unknown-attribute-1": { "type": "string" }, "unknown-attribute-2": { "type": "string" }, ... } } }
Any ideas please, or other way to reach the same?
-
Alexey Sh. over 3 yearsI'm getting error "Property 'patternProperties' is not allowed".
-
pink spikyhairman over 3 years@AlexeySh. please post your full JSON and I will take look
-
Alexey Sh. over 3 yearsexactly copypaste of your answer
-
pink spikyhairman over 3 years@AlexeySh. my first guess would be if you're using JSON Schema or OpenAPI. If JSON Schema, then you should use a recent version. If OpenAPI, a bit of Googling shows patternProperties did not get into OpenAPI as of version 3. Maybe there's a later version.
-
Alexey Sh. over 3 yearsit seems like because I was using swagger and it doesn't support the latest schema
-
redDevil over 2 yearsthis did work me, but without the
anyOf
andadditionalProperties
as well