问题描述
我正在尝试验证json文件,该文件具有一个元素,该元素的属性包含应在json另一部分中存在的值.我正在使用jsonschema Draft 07.
I'm trying to validate json files which have an element that has a property which contains a value that should exist in another part of the json. I'm using jsonschema Draft 07.
这是一个简单的小示例,显示了我要在数据中验证的场景.
This is a simple little example that shows the scenario I'm trying to validate in my data.
{
"objects": {
"object1": {
"colorKey": "orange"
}
},
"colors": {
"orange": {
"red": "FF",
"green": "AF",
"blue": "00"
}
}
}
如何验证colorKey的值"(在本例中为"orange")是否作为"colors"对象的属性存在?数据不是存储在数组中,而是存储在定义的属性中.
How can I validate that the 'value' of colorKey (in this case 'orange') actually exists as a property of the 'colors' object? The data isn't stored in arrays, just defined properties.
推荐答案
用于官方JSON架构...您无法检查数据中的键是否与数据值相同.您无法从JSON实例提取数据值以在JSON模式中使用.
For official JSON Schema...You cannot check that a key in the data is the same as a value of the data.You cannot extract the value of data from your JSON instance to use in your JSON Schema.
话说回来,最流行的验证器ajv实现了一些非官方的扩展.其中之一是$ data.
That being said, ajv, the most popular validator, implements some unofficial extensions. One of which is $data.
摘自以下示例: https://github.com/epoberezkin/ajv#data-reference
var ajv = new Ajv({$data: true});
var schema = {
"properties": {
"smaller": {
"type": "number",
"maximum": { "$data": "1/larger" }
},
"larger": { "type": "number" }
}
};
var validData = {
smaller: 5,
larger: 7
};
ajv.validate(schema, validData); // true
这不适用于使用您的架构的其他任何人.
This would not work for anyone else using your schemas.
这篇关于表示对于给定的属性值,应该使用json模式存在具有相同名称的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!