sagold / json-schema-library

Customizable and hackable json-validator and json-schema utilities for traversal, data generation and validation
MIT License
164 stars 19 forks source link

Wrongful Error on chained negative logic If cases #44

Closed dpoeira91 closed 9 months ago

dpoeira91 commented 10 months ago

When validating an object against a JSON schema that uses conditional constraints, the library appears to be incorrectly flagging valid combinations as invalid.

Example Schema:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "http://example.com/schemas/animal_traits",
  "type": "object",
  "properties": {
    "animal_species": {
      "enum": ["cat", "eagle"]
    },
    "diet_type": {
      "enum": ["carnivore", "omnivore"]
    },
    "habitat_type": {
      "enum": ["forest", "mountain"]
    }
  },
  "allOf": [
    {
      "if": {
        "not": {
          "properties": {
            "animal_species": {
              "const": "cat"
            }
          }
        }
      },
      "then": {
        "properties": {
          "diet_type": {
            "const": "carnivore"
          }
        }
      }
    },
    {
      "if": {
        "not": {
          "properties": {
            "diet_type": {
              "const": "carnivore"
            },
            "animal_species": {
              "const": "cat"
            }
          }
        }
      },
      "then": {
        "properties": {
          "habitat_type": {
            "const": "mountain"
          }
        }
      }
    }
  ]
}

Object to validate:

{
  "animal_species": "cat",
  "diet_type": "omnivore",
  "habitat_type": "mountain"
}

Based on the provided schema, the object should be valid:

  1. The animal_species is "cat", so the diet_type can be either "carnivore" or "omnivore".
  2. Given that diet_type is "omnivore" and animal_species is "cat", habitat_type should be "mountain".

However, when validating the object against the schema using the json-schema-library, an error is thrown indicating that diet_type must be "carnivore". This is contrary to the schema's specifications and seems to indicate an issue in how the library handles the conditional constraints.

Would appreciate any assistance in resolving this. Thank you!

sagold commented 9 months ago

Hi Diogo.

Thank you for reporting this issue. I can verify that this is a bug within json-schema-library allOf validation.

sagold commented 9 months ago

This issue has been fixed and is published with json-schema-library@9.1.1.

Can you verify that your issue has been resolved?

dpoeira91 commented 9 months ago

Just tested this out with the new version, seems to be working for my use-case. Thank you very much! 🙌

sagold commented 9 months ago

Thank you for your feedback!