0

I have a use case where I want to check the keys present in JSON, depending on the value of a different key.

Example JSON-1:

{ 
  "key_name" : "value1",
  "foo" : "random_value1"
}

Example JSON-2:

{ 
  "key_name" : "value2",
  "bar" : "random_value2"
}

There are 2 rules here:

Rule 1. If the value of "key_name" is "value1" then only "foo" key should be present in JSON.

Rule 2. If the value of "key_name" is "value2", then only "bar" key should be present in JSON.

Now, as per the rules, the following JSON's are invalid, and should raise an error.

{ 
  "key_name" : "value1",
  "foo" : "random_value1",
  "bar" : "random_value2"
}

OR

{ 
  "key_name" : "value2",
  "bar" : "random_value2",
  "foo" : "random_value"
}

I have written the JSON Schema for validating these JSON as per this question.

But if I use this, I get the following error:

JSON is not valid under any of the given schemas.

While this solves the purpose, this error is not exactly explainable on why the JSON is not valid. I am expecting some error like:

"Additional properties are not allowed ('bar' was unexpected)"

This is the default error whenever any additional key is present

How to go about doing it?

  • All error messages are implementation specific. Sorry. – Relequestual Apr 27 '20 at 09:02
  • Does this answer your question? [Is there a way to raise an error for any additional key present in JSON if I am using the if-else condition of JSON Schema?](https://stackoverflow.com/questions/61451539/is-there-a-way-to-raise-an-error-for-any-additional-key-present-in-json-if-i-am) – Ether Apr 28 '20 at 17:00
  • In the solutions of the question that you mentioned, I am unable to get the "name" of the additional key in the JSON. It will just tell you that the JSON is not valid and the keys provided exceed the maximum count. – Himani Garg Apr 29 '20 at 18:11

0 Answers0