The rest service response I am working with is similar to following example, I have only included 3 fields here but there are many more:
{ "results": [ { "type": "Person", "name": "Mr Bean", "dateOfBirth": "14 Dec 1981" }, { "type": "Company", "name": "Pi", "tradingName": "Pi Engineering Limited" } ] }
I want to write a JSON schema file for above (draft-04) which will explicitly specify that:
if type == Person then list of required properties is ["type", "name", "dateOfBirth", etc] OR if type == "Company" then list of required properties is ["type", "name", "tradingName", etc]
However am unable to find any documentation or example of how to do it.
Currently my JSON schema looks like following:
{ "$schema": "http://json-schema.org/draft-04/schema", "type": "object", "required": ["results" ], "properties": { "results": { "type": "array", "items": { "type": "object", "required": ["type", "name"], "properties": { "type": { "type": "string" }, "name": { "type": "string" }, "dateOfBirth": { "type": "string" }, "tradingName": { "type": "string" } } } } } }
Any pointers/examples of how I should handle this.
JSON Schema is a JSON media type for defining the structure of JSON data. JSON Schema provides a contract for what JSON data is required for a given application and how to interact with it. JSON Schema is intended to define validation, documentation, hyperlink navigation, and interaction control of JSON data.
At the top of the file, you can specify the schema's id, the schema that should be used to validate the format of your schema, and a descriptive title. These are all defined using the keywords id, $schema and title, all of which are provided in the draft JSON Schema.
$ref. A schema can reference another schema using the $ref keyword. The value of $ref is a URI-reference that is resolved against the schema's Base URI. When evaluating a $ref , an implementation uses the resolved identifier to retrieve the referenced schema and applies that schema to the instance.
I think the recommended approach is the one shown in Json-Schema web, Example2. You need to use an enum to select schemas "by value". In your case it would be something like:
{ "type": "object", "required": [ "results" ], "properties": { "results": { "type": "array", "items": { "oneOf": [ { "$ref": "#/definitions/person" }, { "$ref": "#/definitions/company" } ] } } }, "definitions": { "person": { "properties": { "type": { "enum": [ "person" ] }, "name": {"type": "string" }, "dateOfBirth": {"type":"string"} }, "required": [ "type", "name", "dateOfBirth" ], "additionalProperties": false }, "company": { "properties": { "type": { "enum": [ "company" ] }, . . . } } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With