propertyNames : Schema
propertyNames
SchemaValidation succeeds if the schema validates against every property name in the instance.
Value |
This keyword must be set to a valid JSON Schema
Hint: Use the jsonschema metaschema and jsonschema lint commands to catch keywords set to invalid values
|
---|---|
Kind | Applicator |
Applies To | Object |
Base Dialect | 2020-12 |
Changed In | None |
Introduced In | Draft 6 |
Vocabulary | Applicator |
Specification | https://json-schema.org/draft/2020-12/json-schema-core.html#section-10.3.2.4 |
Metaschema | https://json-schema.org/draft/2020-12/meta/applicator |
Official Tests | draft2020-12/propertyNames.json |
Default |
{}
|
Annotation | None |
Affected By | None |
Affects | None |
Also See |
|
The propertyNames
keyword restricts object instances to only define
properties whose names match the given schema. This keyword is evaluated
against every property of the object instance, independently of keywords that
indirectly introduce property names such as properties
and patternProperties
.
Common Pitfall
As per the JSON grammar, the name of an object property
must be a string. Therefore, setting this keyword to a schema that makes use of
keywords that only apply to types other than strings (such as the
properties
keyword) is either
meaningless or leads to unsatisfiable schemas. Conversely, explicitly setting
the type
keyword to string
is redundant.
Best Practice
This keyword is useful when describing JSON objects whose
properties cannot be known in advance. For example, allowing extensions that
must adhere to a certain name convention. If that’s not the case, prefer
explicitly listing every permitted property using the properties
or patternProperties
keywords, and potentially closing
the object by setting the additionalProperties
keyword to false
.
Remember that JSON Schema is a constraint-driven language.
Therefore, non-object instances successfully validate against this
keyword. If needed, make use of the type
keyword to constraint
the accepted type accordingly.
Examples
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"propertyNames": { "pattern": "^[a-z]*$" }
}
{ "foo": "bar" }
{}
{ "CamelCase": true, "alphanumeric123": false }
"Hello World"
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"propertyNames": { "type": "array" }
}
{ "foo": "bar" }
{}
"Hello World"
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"propertyNames": { "pattern": "^b" },
"properties": {
"foo": { "type": "integer" },
"bar": { "type": "integer" }
}
}
{ "foo": 1 }
{ "bar": "should have been an integer" }
{ "baz": "qux" }