Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON schema reference another element in the document

Is there a way to express reference to another element in the same JSON document using JSON schema? The title might be a bit confusing, but i'm not looking for the "$ref" attribute, which references another type, but I'm curious, if there is a way, to reference another element in the document using a specified field. I know this is possible to enforce using xsd for xml documents, not sure about JSON.

I want to do something like this:

{
  "people": [
    { "id": "1", "name": "A" },
    { "id": "2", "name": "B" },
    { "id": "3", "name": "C" }
  ],
  "chosenOne": "1" // I want the schema to enforce a person ID here
}

I have been looking at the schema definition of v4: http://json-schema.org/draft-04/schema but didn't find anything, that looks like what I'm trying to do. Did I just miss it?

like image 571
Balázs Édes Avatar asked Jan 24 '16 18:01

Balázs Édes


1 Answers

What you want is that you describe a reference ($ref) in the object your schema is describing.

kind of like this

{
    "people": []
    "chosenOne": { $ref: "#1"}
}

(or maybe a pointer if you want the value of the Id (https://json-spec.readthedocs.io/pointer.html)

I know of no direct way to do this but you might be able to use the pattern or oneof properties to force it being the right value. Kind of like this

"properties": {
    "chosenOne"
         "type": "string",
         "oneOf": ["1","2","3"]
         ]
     },
}

Similarly you could force the value of the property to be a reference pattern. That said since there is no reference value type (http://www.tutorialspoint.com/json/json_data_types.htm) only number or string you can't guarantee the meaning of the value. You can just guarantee that if follows some kind of reference pattern.

If you need more than what json schema's can give you you might want to look in odata for example. OData has some extra things so you can describe an entitySet and then define a navigation property to that set. It does however force you to follow the odata structure so you aren't as free as you would be with a regular json schema.

like image 107
Batavia Avatar answered Sep 20 '22 08:09

Batavia