Mehdi Pourfar
Mehdi Pourfar

Reputation: 518

How to validate object values in jsonschema?

Suppose I have a json like this:

{"1": {"first_name": "a", "last_name": "b"},
 "2": {"first_name": "c", "last_name": "d"}}

As you can see, values have such schema:

{"type": "object",
 "properties": {
    "first_name": {"type": "string"},
    "last_name": {"type": "string"}
  },
  "additionalProperties": false,
  "required": ["first_name", "last_name"]}

I want to know how can I define a schema which can validate the above json?

Upvotes: 2

Views: 1147

Answers (1)

Relequestual
Relequestual

Reputation: 12355

The additionalProperties takes a JSON Schema as it's value. (Yes, a boolean is a valid JSON Schema!)

Let's recap what the additionalProperties keyword does...

The behavior of this keyword depends on the presence and annotation results of "properties" and "patternProperties" within the same schema object. Validation with "additionalProperties" applies only to the child values of instance names that do not appear in the annotation results of either "properties" or "patternProperties".

For all such properties, validation succeeds if the child instance validates against the "additionalProperties" schema.

https://json-schema.org/draft/2020-12/json-schema-core.html#additionalProperties

In simplest terms, if you don't use properties or patternProperties within the same schema object, the value schema of additionalProperties applies to ALL values of the applicable object in your instance.

As such, you only need to nest your existing schema as follows.

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "additionalProperties": YOUR SCHEMA
}

Upvotes: 2

Related Questions