json-schema-spec icon indicating copy to clipboard operation
json-schema-spec copied to clipboard

equality between properties

Open vasile-baluta opened this issue 2 years ago • 4 comments

Hi!

If I have json like this

{ "property1": "value1", "property2": "value1" }

How will a schema look like that invalidates the json if property1 has same value as property2?

vasile-baluta avatar Jul 05 '23 13:07 vasile-baluta

Unfortunately, this is one of the things JSON Schema isn't currently capable of expressing. We would need a new keyword similar to uniqueItems, but works on objects instead of arrays.

jdesrosiers avatar Jul 05 '23 19:07 jdesrosiers

@vasile-baluta are you asking to validate whether any two properties have the same values, or just that property1 and property2 need to be different while other properties present in the instance could have any value.

If the first (all unique property values), then what @jdesrosiers said.

If the second (just property1 needs to be different from property2), then there is a solution if you're using .Net. I've defined a vocabulary that allows you to reference data from the instance and use it in a validation via a new keyword: data. Other implementations have a variation of this (typically $data), but those have other drawbacks.

A schema that would invalidate the instance you posted would be something like this:

{
  "$schema": "https://json-everything.net/meta/data-2022",
  "type": "object",
  "properties": {
    "property1": { "type": "string" },
    "property2": {
      "type": "string",
      "not": {
        "data": {
          "const": "/property1"
        }
      }
    }
  }
}

The link to the vocabulary above explains how this works in a bit more detail, but basically, the values of data are used to build a subschema. In this case, we pull the value from property1 and put it under the const keyword. That gives us a schema that we can use to evaluate the instance. Since we're using the not keyword, the validation result is inverted.

So this says

  • property1 should be a string
  • property2 should be a string
  • property2 should not be whatever property1 is

My hope is that eventually other implementations will support this vocabulary, but I haven't seen that yet.

You can test this on https://json-everything.net/json-schema.

gregsdennis avatar Jul 05 '23 21:07 gregsdennis

Thanks @gregsdennis !

I use Python and I solved it using a custom validator but I plan to create a repository at GitHub to show my solution.

BR

vasile-baluta avatar Jul 07 '23 10:07 vasile-baluta

@vasile-baluta it would be helpful for the project if we understood your need so that we can decide whether a proper solution needs to be added to JSON Schema. If you can find the time, we'd appreciate a summary. Otherwise, I think I'll close this issue as resolved.

gregsdennis avatar Sep 14 '23 06:09 gregsdennis