Search code examples
jsonschema

How to include checks for a number embedded in a string in json schema?


I have a field version in my json schema that represents a SchemaVer (e.g. 1-0-1). I am now adding a field, it is backwards compatible so I bump the last number 1-0-2. But I want to make sure that this new field is only allowed when version is at least 1-0-2.

I can't use a pattern (or rather, I don't want to enumerate all versions) since I'd have to specify the idea: For X-Y-Z, this field is valid when Y >= 0 and Z >= 2.

Is this something that is possible in JSON schema? Or should I instead go for three fields denoting the version instead?

I looked for using capture groups with jsonschema, but couldn't find anything.


Solution

  • You can do something like this with the regex for semver

    stick tap for this answer: https://stackoverflow.com/a/72900791/8564731

    This states, version must be 1.0.2 or greater for any other properties to be defined.

    additionalProperties: false if version is <=1.0.1

    This also gives you the ability to use suffix versioning like normal semver

    • 1.0.1-beta
    • 1.0.2-rc
    • etc...
    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "oneOf": [
        {
          "type": "object",
          "properties": {
            "version": {
              "type": "string",
              "pattern": "^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[2-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$"
            },
            "newField": {
              "type": "string"
            }
          },
          "required": [
            "version",
            "newField"
          ]
        },
        {
          "type": "object",
          "properties": {
            "version": {
              "type": "string",
              "pattern": "^(0|[1]\\d*)\\.[0]\\.(0|[1]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$"
            }
          },
          "required": ["version"],
          "additionalProperties": false
        }
      ]
    }
    

    Capture groups are inherently available in JSON Schema with the pattern property which subscribes to ECMA262 regex specification