a.cayzer
a.cayzer

Reputation: 289

How to validate number of properties in JSON schema

I am trying to create a schema for a piece of JSON and have slimmed down an example of what I am trying to achieve.

I have the following JSON schema:

{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Set name",
"description": "The exmaple schema",
"type": "object",
"properties": {
    "name": {
        "type": "string"
    }
},
"additionalProperties": false
}

The following JSON is classed as valid when compared to the schema:

{
"name": "W",
"name": "W"
}

I know that there should be a warning about the two fields having the same name, but is there a way to force the validation to fail if the above is submitted? I want it to only validate when there is only one occurrence of the field 'name'

Upvotes: 1

Views: 2506

Answers (2)

Jason Desrosiers
Jason Desrosiers

Reputation: 24479

This is outside of the responsibility of JSON Schema. JSON Schema is built on top of JSON. In JSON, the behavior of duplicate properties in an object is undefined. If you want to get warning about this you should run it through a separate validation step to ensure valid JSON before passing it to a JSON Schema validator.

Upvotes: 1

vearutop
vearutop

Reputation: 4072

There is a maxProperties constraint that can limit total number of properties in an object.

Though having data with duplicated properties is a tricky case as many json decoding implementions would ignore duplicate.

So your JSON schema validation lib would not even know duplicate existed.

Upvotes: 1

Related Questions