Is it possible to be agnostic on the properties' names?

Viewed 40

Let's say I want to have a schema for characters from a superhero comics. I want the schema to validate json objects like this one:

{
  "Name": "Roberta",
  "Age": 15,
  "Abilities": {
    "Super_Strength": {
      "Cost": 10,
      "Effect": "+5 to Strength"
    }
  }
}

My idea is to do it like that:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "characters_schema.json",
  "title": "Characters",
  "description": "One of the characters for my game",
  "type": "object",
  "properties": {
    "Name": {
      "type": "string"
    },
    "Age": {
      "type": "integer"
    },
    "Abilities": {
      "description": "what the character can do",
      "type": "object"
    }
  },
  "required": ["Name", "Age"]
}

And use a second schema for abilities:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "abilities_schema.json",
  "title": "Abilities",
  "type": "object",
  "properties": {
    "Cost": {
      "description": "how much mana the ability costs",
      "type": "integer"
    },
    "Effect": {
      "type": "string"
    }
  }
}

But I can't figure how to merge Abilities in Characters. I could easily tweak the schema so that it validates characters formatted like:

{
  "Name": "Roberta",
  "Age": 15,
  "Abilities": [
    {
      "Name": "Super_Strength"
      "Cost": 10,
      "Effect": "+5 to Strength"
    }
  ]
}

But as I need the name of the ability to be used as a key I don't know what to do.

1 Answers

You need to use the additionalProperties keyword.

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".

https://json-schema.org/draft/2020-12/json-schema-core.html#rfc.section.10.3.2.3

In laymans terms, if you don't define properties or patternProperties the schema value of additionalProperties is applied to all values in the object at that instance location.

Often additionalProperties is only given a true or false value, but rememeber, booleans are valid schema values.

If you have constraints on the keys for the object, you may wish to use patternPoperties followed by additionalProperties: false.

Related