Json 架构。如何根据另一个 属性 值验证 属性 键?

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

数据:

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

如何通过 "languages" 属性 定义验证文件 属性 中键名的架构?

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

绝对不可能用json模式来表达这样的约束。

您可以使用一些验证器支持的自定义关键字来定义额外的数据约束,例如Ajv(我是作者):

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));

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