【发布时间】:2020-07-15 21:55:39
【问题描述】:
假设我有架构和 JSON:
JSON 架构:
const schema = {
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": [ "countries" ],
"definitions": {
"europeDef": {
"type": "object",
"required": ["type"],
"properties": { "type": {"const": "europe"} }
},
"asiaDef": {
"type": "object",
"required": ["type"],
"properties": { "type": {"const": "asia"} }
}
},
"properties": {
"countries": {
"type": "array",
"items": {
"oneOf":[
{ "$ref": "#/definitions/europeDef" },
{ "$ref": "#/definitions/asiaDef"}
]
}
}
}
}
JSON:
const data = {
"countries":[
{"type": "asia1"},
{"type": "europe1"}
]
}
const isValid = ajv.validate(schema, data); //schema, data
if(! isValid){
console.log(ajv.errors);
}
以及错误信息:
[ { keyword: 'const',
dataPath: '/countries/0/type',
schemaPath: '#/definitions/europeDef/properties/type/const',
params: { allowedValue: 'europe' },
message: 'should be equal to constant' },
{ keyword: 'const',
dataPath: '/countries/0/type',
schemaPath: '#/definitions/asiaDef/properties/type/const',
params: { allowedValue: 'asia' },
message: 'should be equal to constant' },
{ keyword: 'oneOf',
dataPath: '/countries/0',
schemaPath: '#/properties/countries/items/oneOf',
params: { passingSchemas: null },
message: 'should match exactly one schema in oneOf' },
{ keyword: 'const',
dataPath: '/countries/1/type',
schemaPath: '#/definitions/europeDef/properties/type/const',
params: { allowedValue: 'europe' },
message: 'should be equal to constant' },
{ keyword: 'const',
dataPath: '/countries/1/type',
schemaPath: '#/definitions/asiaDef/properties/type/const',
params: { allowedValue: 'asia' },
message: 'should be equal to constant' },
{ keyword: 'oneOf',
dataPath: '/countries/1',
schemaPath: '#/properties/countries/items/oneOf',
params: { passingSchemas: null },
message: 'should match exactly one schema in oneOf' } ]
我的问题是,因为我已经导出了这个模式,所以我几乎可以理解这个错误。但是对于第三者来说,肯定需要一些时间才能弄清楚(如果架构/错误更复杂,可能需要更多时间)。
有什么方法可以让它更加用户友好?
【问题讨论】:
-
@JasonDesrosiers 这是一个示例,但实际上我的 json 模式更复杂,由 if-then、enum、oneOf、allOf 等组成,并且可能不可能一直按该顺序排列.此外,我们不能将上述错误作为响应呈现给最终用户,因为它更难理解且对用户不友好。有什么选择吗?
标签: jsonschema json-schema-validator ajv