我从 API 收到此错误响应:
[HTTP 400] - BAD_REQUEST 0 [53015] - sender name invalid value: almir1 [53044] - credit card holder name invalid value: almir
如何将此响应转换为 JavaScript 中的对象或数组?
例如:
var errors = [
{key : 53015: message: "sender name invalid value"},
{key : 53044: message: "credit card holder name invalid value: almir"}
];
最佳答案
这应该可以解决问题:
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];
}
输出:
{
"53015": "sender name invalid value: almir1 ",
"53044": "credit card holder name invalid value: almir",
"HTTP 400": "BAD_REQUEST 0 "
}
要创建键/消息数组,请使用它
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]
});
}
输出:
[
{
"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"
}
]
关于javascript - 如何转换对象或数组中的字符串消息错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49761142/