如何转换对象或数组中的字符串消息错误?

时间:2018-04-10 19:01:46

标签: javascript json

我从api收到此错误回复:

  

[HTTP 400] - BAD_REQUEST 0 [53015] - 发件人名称无效值:almir1   [53044] - 信用卡持有人姓名无效值:almir

我怎样才能在javascript中将此响应转换为对象或数组?

例如:

     var errors = [
        {key : 53015: message: "sender name invalid value"},
        {key : 53044: message: "credit card holder name invalid value: almir"}
    ];

3 个答案:

答案 0 :(得分:2)

这应该可以解决问题:

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

答案 1 :(得分:0)

你可以使用:var aRes = str.split('['); 获取由'['拆分的字符串数组,然后将这些aRes字符串进一步处理为所需的json“错误”对象。

答案 2 :(得分:0)

要制作数组,您可以匹配每个错误的模式:

var regex = /\[\d+\]\s\-\s([^\[+]+)/gi
errorMessage.match(regex);

// returns 
// [ '[53015] - sender name invalid value: almir1 ',
//  '[53044] - credit card holder name invalid value: almir' ]

如果要将其转换为对象,可以使用捕获组:

var regex = /\[(\d+)\]\s\-\s([^\[]+)/gi
var errors = {};
var error;
while (error = regex.exec(errorMessage)) {
  errors[error[1]] = error[2];
}