我在使用 express 框架的 NodeJS 应用程序上捕获来自 Mongoose 的 JSON 错误:
{
"err": {
"errors": {
"last_name": {
"message": "Path `last_name` is required.",
"name": "ValidatorError",
"properties": {
"message": "Path `last_name` is required.",
"type": "required",
"path": "last_name"
},
"kind": "required",
"path": "last_name"
},
"first_name": {
"message": "Path `first_name` is required.",
"name": "ValidatorError",
"properties": {
"message": "Path `first_name` is required.",
"type": "required",
"path": "first_name"
},
"kind": "required",
"path": "first_name"
},
"password": {
"message": "Path `password` (`iam`) is shorter than the minimum allowed length (6).",
"name": "ValidatorError",
"properties": {
"message": "Path `password` (`iam`) is shorter than the minimum allowed length (6).",
"type": "minlength",
"minlength": 6,
"path": "password",
"value": "iam"
},
"kind": "minlength",
"path": "password",
"value": "iam"
}
},
"_message": "User validation failed",
"message": "User validation failed: last_name: Path `last_name` is required., first_name: Path `first_name` is required., password: Path `password` (`iam`) is shorter than the minimum allowed length (6).",
"name": "ValidationError"
}
}
如何获取properties
中每个错误的type
和path
,我试过forEach()
方法,但它不起作用,是否有任何其他方法可以循环遍历此 JSON?
最佳答案
找到键,迭代键。将这些结果添加到某些数据结构中。
我选择在键上使用 map
并添加到数组中。
const errors = {
"err": {
"errors": {
"last_name": {
"message": "Path `last_name` is required.",
"name": "ValidatorError",
"properties": {
"message": "Path `last_name` is required.",
"type": "required",
"path": "last_name"
},
"kind": "required",
"path": "last_name"
},
"first_name": {
"message": "Path `first_name` is required.",
"name": "ValidatorError",
"properties": {
"message": "Path `first_name` is required.",
"type": "required",
"path": "first_name"
},
"kind": "required",
"path": "first_name"
},
"password": {
"message": "Path `password` (`iam`) is shorter than the minimum allowed length (6).",
"name": "ValidatorError",
"properties": {
"message": "Path `password` (`iam`) is shorter than the minimum allowed length (6).",
"type": "minlength",
"minlength": 6,
"path": "password",
"value": "iam"
},
"kind": "minlength",
"path": "password",
"value": "iam"
}
},
"_message": "User validation failed",
"message": "User validation failed: last_name: Path `last_name` is required., first_name: Path `first_name` is required., password: Path `password` (`iam`) is shorter than the minimum allowed length (6).",
"name": "ValidationError"
}
}
let output = Object.keys(errors.err.errors).map(key => { return {type:errors.err.errors[key].properties.type, path:errors.err.errors[key].properties.path} });
console.log(output);
关于javascript - 如何在 Javascript 上解析这个 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56210602/