Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Schema - require all properties

Tags:

jsonschema

The required field in JSON Schema

JSON Schema features the properties, required and additionalProperties fields. For example,

{     "type": "object",     "properties": {         "elephant": {"type": "string"},         "giraffe": {"type": "string"},         "polarBear": {"type": "string"}     },     "required": [         "elephant",         "giraffe",         "polarBear"     ],     "additionalProperties": false } 

Will validate JSON objects like:

{     "elephant": "Johnny",     "giraffe": "Jimmy",     "polarBear": "George" } 

But will fail if the list of properties is not exactly elephant, giraffe, polarBear.

The problem

I often copy-paste the list of properties to the list of required, and suffer from annoying bugs when the lists don't match due to typos and other silly errors.

Is there a shorter way to denote that all properties are required, without explicitly naming them?

like image 433
Adam Matan Avatar asked Jun 16 '15 12:06

Adam Matan


People also ask

What is required in JSON Schema?

Required PropertiesThe required keyword takes an array of zero or more strings. Each of these strings must be unique. In Draft 4, required must contain at least one string.

Is JSON Schema necessary?

It's often necessary for applications to validate JSON objects, to ensure that required properties are present and that additional validation constraints (such as a price never being less than one dollar) are met.

What is $id in JSON Schema?

$id is a reserved keyword. It serves for: Declaring an identifier for the schema or subschema. Declaring a base URL against which $ref URLs are resolved.

What are properties in JSON?

A JSON object contains zero, one, or more key-value pairs, also called properties. The object is surrounded by curly braces {} . Every key-value pair is separated by a comma. The order of the key-value pair is irrelevant.


1 Answers

You can just use the "minProperties" property instead of explicity naming all the fields.

{     "type": "object",     "properties": {         "elephant": {"type": "string"},         "giraffe": {"type": "string"},         "polarBear": {"type": "string"}     },     "additionalProperties": false,     "minProperties": 3 } 
like image 170
San Jay Avatar answered Sep 23 '22 17:09

San Jay