0
votes

I have the following json-schema which defines 3 types of toys, to be used with this json GUI builder (github):

{
    "id": "http://some.site.somewhere/entry-schema#",
    "$schema": "http://json-schema.org/draft-04/schema#",
    "description": "schema for toys in game",
    "type": "object",
    "required": [ "type" ],
    "properties": {
        "sawObj": {
            "type": "object",
            "oneOf": [
                { "$ref": "#/definitions/rect" },
                { "$ref": "#/definitions/circle" },
                { "$ref": "#/definitions/img" }
            ]
        }
    },
    "definitions": {
        "rect": {
            "properties": {
                "width": { "type": "integer" },
                "height": { "type": "integer" },
                "weight": { "type": "integer" }
            },
            "required": [ "width", "height", "weight" ],
            "additionalProperties": false
        },
        "circle": {
            "properties": {
              "radius": { "type": "integer" },
              "weight": { "type": "integer" }
            },
            "required": [ "radius", "weight" ],
            "additionalProperties": false
        },
        "img": {
            "properties": {
              "path": { "type": "string" },
              "width": { "type": "integer" },
              "height": { "type": "integer" },
              "weight": { "type": "integer" }
            },
            "required": [ "path", "width", "height", "weight" ],
            "additionalProperties": false
        }
    }
}

If I pick the circle object for example I get an output:

{
  "sawObj": {
    "radius": 0,
    "weight": 0
  }
}

I want to add a value "type" which would always be constrained to reflect the users chosen type. So instead something like this:

{
  "sawObj": {
    "type": "circle",
    "radius": 0,
    "weight": 0
  }
}

Where the type is automatically determined by the users choice from the oneOf properties section.

How can I do this with json-schema?

1

1 Answers

0
votes

I was able to do this the enum value and only allowing a single value representing the type. I also set the type value as required so it is always automatically set to 'circle'.

"circle": {
    "properties": {
        "radius": {
            "type": "integer"
        },
        "weight": {
            "type": "integer"
        },
        "type": {
            "type": "string",
            "enum": ["circle"]
        }
    },
    "required": ["radius", "weight", "type"],
    "additionalProperties": false
}

Note: I want to point out this solution is not ideal. I'm hoping to find a better way to do this.