gpt4 book ai didi

javascript - 如何从 AJV 错误中获取 "title"?

转载 作者:行者123 更新时间:2023-11-30 09:29:15 24 4
gpt4 key购买 nike

我有一个如下所示的 JSON 模式:

{
"required": [
"instructions"
],
"properties": {
"instructions": {
"title": "Instructions",
"minItems": 3,
"type": "array",
"items": {
"required": [
"typeId",
"teamId",
"disciplineId"
],
"properties": {
"typeId": {
"minimum": 1,
"title": "Appointment Type",
"type": "integer"
},
"teamId": {
"minimum": 1,
"title": "Team",
"type": "integer"
},
"disciplineId": {
"minimum": 1,
"title": "Discipline",
"type": "integer"
},
"prefClinicianId": {
"title": "Pref. Clinician",
"anyOf": [
{
"type": "null"
},
{
"minimum": 1,
"type": "integer"
}
]
},
"prefTime": {
"title": "Pref. Time",
"anyOf": [
{
"type": "null"
},
{
"type": "integer"
}
]
},
"childRequired": {
"title": "Child Req'd",
"type": "boolean"
}
},
"type": "object"
}
}
},
"type": "object"
}

如您所见,我已将 title 添加到所有属性中。但是,我返回的错误对象如下所示:

[
{
"keyword": "minItems",
"dataPath": ".instructions",
"schemaPath": "#/properties/instructions/minItems",
"params": {
"limit": 3
},
"message": "should NOT have less than 3 items"
},
{
"keyword": "type",
"dataPath": ".instructions[0].typeId",
"schemaPath": "#/properties/instructions/items/properties/typeId/type",
"params": {
"type": "integer"
},
"message": "should be integer"
},
{
"keyword": "type",
"dataPath": ".instructions[0].teamId",
"schemaPath": "#/properties/instructions/items/properties/teamId/type",
"params": {
"type": "integer"
},
"message": "should be integer"
},
{
"keyword": "type",
"dataPath": ".instructions[0].disciplineId",
"schemaPath": "#/properties/instructions/items/properties/disciplineId/type",
"params": {
"type": "integer"
},
"message": "should be integer"
}
]

如您所见,title 不在其中。如何获取有错误的标题?

请注意,此问题特定于 AJV .

最佳答案

当您创建 AJV 对象时,设置 verbose option to true .

这会将 parentSchema 属性添加到原始架构的 ajv 错误中。它还将添加一个 schema 属性,其中包含导致验证失败的特定架构属性。

这是一个例子:

var ajv = new Ajv({
$data: true,
verbose: true
});

let schema = {
title: 'object title',
type: 'object',
properties: {
str: {
title: "A string property",
type: "string"
}
}
};

let data = {
str: 3
};

ajv.validate(schema, data)

console.log('ERRORS: ', this.ajv.errors)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ajv/5.3.0/ajv.bundle.js"></script>

关于javascript - 如何从 AJV 错误中获取 "title"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47403680/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com