gpt4 book ai didi

javascript - 如何在 Javascript 上解析这个 JSON

转载 作者:行者123 更新时间:2023-11-30 14:01:45 25 4
gpt4 key购买 nike

我在使用 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中每个错误的typepath,我试过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/

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