Almir Júnior
Almir Júnior

Reputation: 61

How to Transform string message error in object or array?

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

Upvotes: 2

Views: 371

Answers (3)

Simone Bembi
Simone Bembi

Reputation: 36

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

Upvotes: 2

Paul
Paul

Reputation: 36319

To make an array, you can match on the pattern of each error:

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

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

If you want to convert that into an object, you can use capture groups:

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

Upvotes: 0

Dan Randolph
Dan Randolph

Reputation: 751

You can use: var aRes = str.split('['); to get an array of strings split by '[' and then further process these aRes strings to the desired json "error" object.

Upvotes: 0

Related Questions