Search code examples
jsonvalidationjsonschemarequired

How can I validate with JSON scheme if object is empty or have required properties?


I want to validate a JSON array of objects with schema in function. These objects must have exactly one of these formats:

  • empty object
  • object with four properties

I tried to wrap required properties in oneOf, but I got the following error: Invalid input: data[1].prop should match exactly one schema in oneOf

{
    "type": "array",
    "items": {
        "type": "object",
        "properties": {
            "prop": {
                "type": "object",
                "properties": {
                    "name": {
                        "prop1": "string"
                    },
                    "type": {
                        "prop2": "string"
                    },
                    "amount": {
                        "prop3": "number"
                    },
                    "operation": {
                        "prop4": "string"
                    }
                },
                "oneOf": [
                    { "required": ["prop1", "prop2", "prop3", "prop4"] },
                    { "required": [] }
                ]
            }
        }
    }
}

Solution

  • I would move the oneOf out so that it's just under the items keyword.

    In one of the subschemas, you have the properties keyword along with the required keyword for those properties plus an additionalProperties: false. This portion would satisfy the "exactly four properties" condition.

    In the other subschema, just identify that it needs to be an object, but don't declare any properties. Use additionalProperties: false in this one, too. This satisfies the "empty object" condition.