layabout
layabout

Reputation: 199

Json schema. How to validate property keys based of another property value?

Data:

{
   "languages": ['en', 'ch'],
   "file": {
      "en": "file1",
      "ch": "file2"
    }
}

How to define a schema that verifies name of keys in file property by "languages" property?

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "description": "",
  "type": "object",
  "properties": {
    "languages": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "file": {
      "type": "object",
      "properties": ????
    }
}

Upvotes: 4

Views: 1733

Answers (2)

esp
esp

Reputation: 7677

You can define additional data constrains using custom keywords, that are supported by some validators, e.g. Ajv (I am the author):

var Ajv = require('ajv');
var ajv = new Ajv;
ajv.addKeyword('validateLocales', {
    type: 'object',
    compile: function(schema) {
        return function(data, dataPath, parentData) {
            for (var prop in data) {
                if (parentData[schema.localesProperty].indexOf(prop) == -1) {
                    return false;
                }
            }
            return true;
        }
    },
    metaSchema: {
        type: 'object',
        properties: {
            localesProperty: { type: 'string' }
        },
        additionalProperties: false
    }
});

var schema = {
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "languages": {
      "type": "array",
      "items": { "type": "string" }
    },
    "file": {
      "type": "object",
      "validateLocales": {
          "localesProperty": "languages"
      },
      "additionalProperties": { "type": "string" }
    }
  }
};

var data = {
   "languages": ['en', 'ch'],
   "file": {
      "en": "file1",
      "ch": "file2"
    }
};

var validate = ajv.compile(schema);
console.log(validate(data));

See https://runkit.com/esp/57d9d419646b97130082de34

Upvotes: 3

erosb
erosb

Reputation: 3141

It is definitely not possible to express such constraint with json schema.

Upvotes: -1

Related Questions