gpt4 book ai didi

javascript - jsonschema-master 验证 json 请求未按预期响应

转载 作者:太空宇宙 更新时间:2023-11-04 01:55:24 25 4
gpt4 key购买 nike

我正在尝试使用 jsonschema-master 来验证使用 Express 通过 POST 请求输入的 json 请求。请参阅下面的代码和示例。

如果属性标签丢失或拼写错误(例如“model”、“areas”、“id”),它会拾取,但如果这些属性的值符合规范,则不会拾取。例如,“model”属性被定义为“premium”或“basic”的枚举类型,但我似乎可以将任何旧字符串放在那里,并且无论如何它都会继续,坐标也被定义为类型号,但它再次忽略这一点,然后错误会通过验证器并进一步导致问题。不确定我错过了什么。

node.js 代码:

var Validator = require('jsonschema-master').Validator;
var v = new Validator();
var bodySchema = {
"model": {
"enum": [ "premium","basic" ]
},
"areas": {
"type":"array",
"items": {
"id": {"type": "string"},
"geometry": {
"type": { "type":"string"},
"coordinates": {
"type":"array",
"items": {
"type":"array",
"items": [
{"type":"number"},
{"type":"number"},
{"type":"number"}
]
}
},
"required" : ["type","coordinates"]
},
"required" : ["id","geometry"]
}
},
"required" : ["model","areas"]
};
var valResult = v.validate(doc.request, bodySchema);
if (valResult.errors.length) {
// Validation failed.
// All processing will now stop.
console.log('Request invalid: '+ doc._id +" - "+valResult.errors);
}

正确的 JSON 请求示例(在 doc.request 中)

{
"model": "premium",
"areas": [
{
"id": "1234",
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
453600.0,
181100.0,
0
],
[
453600.0,
181200.0,
0
],
[
453700.0,
181200.0,
0
],
[
453700.0,
181100.0,
0
],
[
453600.0,
181100.0,
0
]
]
]
}
}
]
}

最佳答案

谢谢大家,但我最终还是解决了。以下是该架构的更正语法:

var bodySchema = {
"type" : "object",
"properties": {
"model": {
"enum": [ "premium","basic" ]
},
"areas": {
"type":"array",
"items": {
"type" : "object",
"properties": {
"id": {"type": "string"},
"geometry": {
"type" : "object",
"properties": {
"type": { "type":"string"},
"coordinates": {
"type":"array",
"items": {
"type":"array",
"items": {
"type":"array",
"items": [
{"type":"number"},
{"type":"number"},
{"type":"number"}
]
}
}
}
},
"required" : ["type","coordinates"]
}
},
"required" : ["id","geometry"]
}
}
},
"required" : ["model","areas"]
};

关于javascript - jsonschema-master 验证 json 请求未按预期响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48184370/

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