Как разобрать этот JSON на Javascript - PullRequest
1 голос
/ 19 мая 2019

У меня есть JSON из-за ошибки Mongoose в приложении NodeJS с экспресс-фреймворком:

{
  "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"
  }
}

Как получить type иpath каждой ошибки внутри properties, я пробовал forEach() метод, но он не работал, есть ли другой способ перебрать этот JSON?

Ответы [ 2 ]

1 голос
/ 19 мая 2019

Другой альтернативой является использование для ... в для обхода свойств объекта err.errors:

Пример:

const input = {"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"}};

for (const k in input.err.errors)
{
    const properties = input.err.errors[k].properties;
    console.log("Error for " + k);
    console.log("> Type: " + properties.type);
    console.log("> Path: " + properties.path);
    console.log("> Message: " + properties.message);
}
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
1 голос
/ 19 мая 2019

Найти ключи, перебрать ключи.Добавьте эти результаты в некоторую структуру данных.

Я решил использовать 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);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...