1

I am a in a transition from this type of jsons:

{
    "id": 1,
    "data": {
         "item_number": "4",
         ...
    }
}

to

{
    "id": 1,
    "data": {
        "itemNumbers": [4],
        ...
    }
}

and I would need a jsonschema that matched both of these jsons.

And here this is:

{
  "properties": {
    "id": {
      "enum": [
        1
      ]
    },
    "data": {
      "anyOf": [
        {
          "properties": {
            "item_number": {
              "enum": [
                "4"
              ]
            }
          }
        },
        {
          "properties": {
            "itemNumbers": {
              "contains": {
                "enum": [
                  4
                ]
              }
            }
          }
        }
      ]
    }
  },
  "required": [
    "id"
  ]
}

Using python jsonschema package, it matches all jsons regardless of item number.

Any help is appreciated.

Relequestual
  • 11,631
  • 6
  • 47
  • 83
Amir
  • 5,996
  • 13
  • 48
  • 61
  • What's the `'enum': ['4']` about? Are you checking for just a single value, or is this an example? – gregsdennis Jan 03 '19 at 05:03
  • yes it is single value (referring you to first json) – Amir Jan 03 '19 at 20:22
  • One other thing I learned when I was researching for this issue is that python package jsonschema 2.6.0 does not support contain: https://github.com/Julian/jsonschema/issues/512 – Amir Jan 03 '19 at 20:25

1 Answers1

1

You'll want to modify your anyOf to oneOf (This won't change anything with your current schema, but makes the intent clearer) and add additionalProperties: false to each of the subschemas.

With your schema, "item_number": "4" fails validation for anyOf[0], but passes for anyOf[1], because there's no constraint for item_number or properties not defined.

additionalProperties: false means that any property not included as a key in properties will cause validation to fail.

Relequestual
  • 11,631
  • 6
  • 47
  • 83