How to define custom object type in json-schema

10,239

While you can't define a new type explicitly, you can define a schema describing what objects of that type look like, and then reference it in your master schema.

{
    "$schema": "http://json-schema.org/draft-07/schema",
    "definitions": {
        "vehicle": {
            "type": "object",
            "properties": {
                "brand": {
                    "type": "string", 
                    "enum": ["ford","toyota"]
                },
                "dateOfManufacture": {
                    "type": "string"
                }
            }
        }
    },
    "type": "object",
    "properties": {
        "primary": { "$ref": "#/definitions/vehicle" },
        "secondary": { "$ref": "#/definitions/vehicle" }
    }
}

This example describes an object with fields primary and secondary that are both of "type" vehicle - i.e. the data must match the schema that describes what a vehicle looks like.

In typed programming languages, the concept of type is used to communicate the shape of data, but also something about the identity of that data - i.e. it gives an identity, or name, to the specific definition of a structure.

struct Foo { int a; string b; }
struct Bar { int a; string b; }

function quux(Foo foo) { ... }

In this dummy example, you can't pass a Bar into Quux, even though it looks just like a Foo. This is because in addition to describing the shape of the data (int a; string b;), the type defines an identity to the data structure.

JsonSchema is about describing the shape of data - i.e. how primitive types are combined in some kind of structure, but says nothing about the identity. It cares about the names of fields and how they are structured, but doesn't care about what you called the schema (or analogously, the name of the struct).

Share:
10,239
Rishi Saraf
Author by

Rishi Saraf

Updated on June 09, 2022

Comments

  • Rishi Saraf
    Rishi Saraf almost 2 years

    Suppose I have couple of objects like Vehicle and Computer.

    {"brand":"Ford", "dateOfManufacture":"23/082015"}
    {"brand":"Apple", "dateOfManufacture":"23/082015"}
    

    I know I can represent vehicle schema like below. However looking at schema doesn't tell me if its of Object type Vehicle or Computer. How can put that information in JSON. Do json-schema provide custom type support . So instead of saying "type": "object" can I say "type": "vehicle".

    {
        "description": "schema validating people", 
        "$schema": "http://json-schema.org/draft-04/schema#",
        "type": "object",
          "properties": { 
                "firstName": {"type": "string"}, 
                "lastName": {"type": "string"}
            }
       }
    }
    

    TIA