1

I am trying to validate a JSON schema using jsonschema lib.

scenario: I need to make sure if a specific value in a property is sent in the parent object, the child(sub-schema) should also get the same value in the same property.

JSON:->

{
"type": "object",
  "properties": {
"action": {
  "enum": [
    "get",
    "post"
  ]
},
"order": {
  "properties": {
    "id": "string",
    "action": {
      "enum": [
        "get",
        "post"
      ]
    }
  }
}},"dependentSchemas": {
"if": {
  "action": {
    "const": "get"
  }
},
"then": {
  "properties": {
    "order": {
      "properties": {
        "action": {
          "const": "get"
        }
      }
    }
  }
}
}
}

Sample test cases: Positive:

{
"action": "get",
"order": {
   "id" : "1"
   "action": "get"
      }
}

Negative:

{
"action": "get",
"order": {
   "id" : "2"
   "action": "post"
      }
}

I am using dependentSchemas to validate the sub-schema:-click here

Murtaza
  • 53
  • 1
  • 5

1 Answers1

1

dependentSchemas isn't going to work for this case. dependentSchemas branches on the presence of a property, not it's value. You need to use if/then to branch on the value of the property.

"allOf": [
  {
    "if": {
      "type": "object",
      "properties": {
        "action": { "const": "get" }
      },
      "required": ["action"]
    },
    "then": {
      "properties": {
        "order": {
          "action": { "const": "get" }
        }
      }
    }
  },
  ... Another if/then just like the first but with "post" ...
]

Note: the type and required keywords are necessary in the if schema for good error messages in extreme cases.

Jason Desrosiers
  • 22,479
  • 5
  • 47
  • 53