Search code examples
javascriptjsonjsonschemaajvtv4

JSON Schema extract the required fields


I need to get a list of the required fields out of a JSON-Schema+Data.

Currently, we are using AJV to get error messages in our forms with JSON Schema and it is working great.

I need a way to get all the required fields (even if filled) in order to mark those fields with * as "required". required fields might change depending on the schema and data combinations.

Also tried hacking tv4 to extract the required fields without success.

Please help.


Example for such schema:

{
  "type": "object",
  "required": [
    "checkbox"
  ],
  "properties": {
    "checkbox": {
      "type": "boolean"
    },
    "textbox": {
      "type": "string"
    }
  },
  "oneOf": [
    {
      "required": [
        "textbox"
      ],
      "properties": {
        "checkbox": {
          "enum": [
            true
          ]
        }
      }
    },
    {
      "properties": {
        "checkbox": {
          "enum": [
            false
          ]
        }
      }
    }
  ],
  "additionalProperties": false
}

Solution

  • Rereading your question the easiest way to do what you'd like would be to

    1. get the Json data on page load,
    2. iterate over the json data to remove valid values (see sample 1),
    3. Call tv4.validateMultiple(data, schema),
    4. check the result object and get the required fields (see sample 2).

    sample 1

    for(let prop in data) {
        if(data.hasOwnProperty(prop) {
            //set value to null, -1, or some other universally bad value
            data[prop]...value = null;
        }
    }
    

    sample 2

    let result = tv4.validateMultiple(data, schema);
    let required = result.errors;