snakile snakile - 3 months ago 8
JSON Question

Enforcing a set of keys in one part of the json to subset a set of keys in another part of the json using a json schema

I'm working on a json schema that defines a family of jsons and there's a certain constraint I'm not sure how to enforce. In a valid json file I'm supposed to have (among other things) two objects. Let's call the first object

entities
and the second object
fields
. The
entities
object also contains an
entityFields
entry which should contain objects whose keys come from the set of keys in
fields
. To make the description clear, I'll demonstrate it using the following valid json:

{
"entities":
{
"entity1":
{
"entityFields":
{
"field1": {},
"field2": {}
}
},
"entity2":
{
"entityFields":
{
"field4": {},
"field5": {}
}
},
"entity3":
{
"entityFields":
{
"field1": {},
"field5": {}
}
}
},
"fields":
{
"field1": {},
"field2": {},
"field3": {},
"field4": {},
"field5": {},
"field6": {}
}
}


Observe that each entity has entity fields coming from the set of fields defined below under
fields
. This is the constraint I'm trying to enforce. In general, how do I enforce the set of keys in one part of my json to be a subset of the set of keys in a different part of the json? Specifically, what should I add to the json schema in order to require this from the set of valid jsons?

Answer

There is definitely no way to carry this out with json schema.

You have the following options:

  • perform the validation manually, without any json schema
  • first traverse your entities and entityFields, programmatically generate a json schema from these, then validate the fields against the generated schema. The entities and entityFields form some naive type system - in this concept, you may want to translate these to an other type system (json schema).