1

I have a string that looks like:

const msg = " [['robot_arm', 'bc1', 'p_09_04_00'], ['operator', 'lc1', 'p_09_15_00'], ['robot_arm', 'oc1', 'p_08_17_00']]"

And I want to split it into an array of arrays of strings, I have tried to split this string as follows:

const msg_obj = new Array(JSON.parse(msg).split("["));
console.log(msg_obj);
for (let act_id in msg_obj) { 
    console.log(msg_obj[act_id]);
}

The problem is that I get unwanted characters/strings inside:

  1. Empty strings "".
  2. commas ,.
  3. square bracket ].

Can you please tell me if there is a better way to split this string into an array of arrays of strings without the unwanted output? thanks in advance.

2 Answers 2

2

The problem is that your single quotes aren't valid JSON. You can easily get the result you want by replacing the quotes before parsing:

const msg = " [['robot_arm', 'bc1', 'p_09_04_00'], ['operator', 'lc1', 'p_09_15_00'], ['robot_arm', 'oc1', 'p_08_17_00']]"

const msg_obj = JSON.parse(msg.trim().replace(new RegExp("'", "g"), "\""));

console.log(msg_obj);
for (let act_id of msg_obj) {
  console.log(act_id);
}

Sign up to request clarification or add additional context in comments.

4 Comments

I get an error: Uncaught SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 5 of the JSON data
Please check my updated solution. I added the .trim() method to trim off excess whitespace. Are you sure that msg matches your real data?
"msg matches your real data?", no, actually I have reduced the msg to make a MWE, thanks.
0

Your const msg is not a valid json string. maybe you can parse this string by this codes :

const msg = " [['robot_arm', 'bc1', 'p_09_04_00'], ['operator', 'lc1', 'p_09_15_00'], ['robot_arm', 'oc1', 'p_08_17_00']]"

msgArr = msg.split("], [").map(item => {  
    return item.trim().split(",").map(val => {
        return val.trim().replace(/\[|\'/g,'');  
    });  
})

example.png

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.