visc
visc

Reputation: 4959

Is it possible to write a generic JSON Schema?

Inside my root JSON object I have many JSON objects of two different types. I'm wondering if there is a way to write a JSON schema to validate these objects without getting specific, i.e. generic schema.

For example, imagine I have the following JSON:

"Profile":
{
    "Name":
    {
        "Type": "String",
        "Value": "Mike",
        "Default": "Sarah",
        "Description": "This is the name of my person."
    }
    "Age":
    {
        "Type": "Number",
        "Value": 27,
        "Default": 18,
        "Description": "This is the age of my person."
    }
}

This Profile JSON object represents a collection of various details about a person. Notice I have two different types of inner Objects, String Objects and Number Objects. Taking this into account, I would now like to create a JSON Schema to validate any of the inner objects without being specifc about which Objects they are, e.g. I don't care that we have "Name" or "Age", I care that we have proper String Objects and Number Objects.

Does JSON Schema give me the ability to do this? How do I write a generic JSON Schema based on the kinds of Objects I have and not specific object names?

Here is what I've got so far:

{
"$schema": "http://json-schema.org/draft-04/schema#",
  "definitions": {
    "StringObject": {
      "type": "object",
      "properties": {
        "Type": {
          "type": "string"
        },
        "Value": {
          "type": "string"
        },
        "Default": {
          "type": "string"
        },
        "Description": {
          "type": "string"
        }
      },
      "required": [
        "Type",
        "Value",
        "Default",
        "Description"
      ]
    }
  }
}

Upvotes: 3

Views: 5183

Answers (1)

Paul Sweatte
Paul Sweatte

Reputation: 24617

Inside my root JSON object I have many JSON objects of two different types. I'm wondering if there is a way to write a JSON schema to validate these objects without getting specific, i.e. generic schema.

Union types are defined to handle this:

A value of the "union" type is encoded as the value of any of the member types.

Union type definition - An array with two or more items which indicates a union of type definitions. Each item in the array may be a simple type definition or a schema.

{
"type":
  ["string","number"]
}

References

Upvotes: 2

Related Questions