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

时间:2016-08-26 13:52:06

标签: json jsonschema

数据:

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

如何定义一个模式,通过"语言"来验证文件属性中的键名。属性?

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

2 个答案:

答案 0 :(得分:2)

您可以使用某些验证程序支持的自定义关键字定义其他数据约束,例如: 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

答案 1 :(得分:0)

绝对不可能用json架构表达这样的约束。