1

i have json like this

{ "user" : ["foo", "bar"] }

i want use if else here

if there "foo" in array user then field admin is required

I've tried it like this

 {
    "$schema": "http://json-schema.org/draft-07/schema",
    "title": "JSON Schema for role",
    "type": "object",
    "properties": {
        "user": {
            "type": ["array"],
          "items" : {
          "type" : "string",
            "enum" : [
            "foo",
              "bar"
            ]
          }
        },
      "admin" : {"type" : "string"},
     "if": {
    "properties": {
      "user": { "const": "foo" }
    },
    "required": ["user"]
  },
  "then": { "required": ["admin"] }
    },"additionalProperties": false}

but not work

0

1 Answer 1

2

const is applicable to single values, but you want to check the contense of an array.

You want contains. contains applies it's value (which is a subschema) to each item in the array, to check at least one of the items is what is expected.

You also needed to have your if and then keywords be part of a schema object. You had them as part of the properties object.

{
  "$schema": "http://json-schema.org/draft-07/schema",
  "title": "JSON Schema for role",
  "type": "object",
  "properties": {
    "user": {
      "type": [
        "array"
      ],
      "items": {
        "type": "string",
        "enum": [
          "foo",
          "bar"
        ]
      }
    },
    "admin": {
      "type": "string"
    }
  },
  "required": [
    "user"
  ],
  "if": {
    "properties": {
      "user": {
        "contains": {
          "type": "string",
          "const": "foo"
        }
      }
    }
  },
  "then": {
    "required": [
      "admin"
    ]
  },
  "additionalProperties": false
}

See it working: https://jsonschema.dev/s/RaxvK

Sign up to request clarification or add additional context in comments.

1 Comment

Welcome! If you consider the linked service helpful, please consider supporting its further development =]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.