3

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"
      ]
    }
  }
}
Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265
visc
  • 4,794
  • 6
  • 32
  • 58

1 Answers1

2

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

Community
  • 1
  • 1
Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265
  • 3
    This answer doesn't quite seem to answer what the OP is asking for. He wants to enforce that `Value` and `Default` are of the same type. See here an example of this not being the case: https://www.jsonschemavalidator.net/s/x70vItRy – dwjohnston Aug 31 '22 at 05:42