I'm receiving this error response from an api:
[HTTP 400] - BAD_REQUEST 0 [53015] - sender name invalid value: almir1 [53044] - credit card holder name invalid value: almir
How could i transform this response to an object or array in javascript?
for example:
var errors = [
{key : 53015: message: "sender name invalid value"},
{key : 53044: message: "credit card holder name invalid value: almir"}
];
This should do the trick:
const text = `[HTTP 400] - BAD_REQUEST 0 [53015] - sender name invalid
value: almir1 [53044] - credit card holder name invalid value: almir`;
let regex = /\[([^\]]+?)\]\s\-\s([^\[]+)/g;
let matches;
const errors = {};
while (matches = regex.exec(text)) {
errors[matches[1]] = matches[2];
}
Output:
{
"53015": "sender name invalid value: almir1 ",
"53044": "credit card holder name invalid value: almir",
"HTTP 400": "BAD_REQUEST 0 "
}
To create a key/message array use this instead
const text = `[HTTP 400] - BAD_REQUEST 0 [53015] - sender name invalid value: almir1 [53044] - credit card holder name invalid value: almir`;
let regex = /\[([^\]]+?)\]\s\-\s([^\[]+)/g;
let matches;
const errors = [];
while (matches = regex.exec(text)) {
errors.push({
key: matches[1],
message: matches[2]
});
}
Output:
[
{
"key": "HTTP 400",
"message": "BAD_REQUEST 0 "
},
{
"key": "53015",
"message": "sender name invalid value: almir1 "
},
{
"key": "53044",
"message": "credit card holder name invalid value: almir"
}
]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments