{ data1: "'opt01', 'opt\'02', 'op,t03'", data2: "plaintext"}
I have the above returned json data.
How can I obtain data1 by an array format so that I can loop the data inside one by one?
{ data1: "'opt01', 'opt\'02', 'op,t03'", data2: "plaintext"}
I have the above returned json data.
How can I obtain data1 by an array format so that I can loop the data inside one by one?
 
    
    If each string in data1 is single quote delimited
var data1 = jsonData.data1;
data1 = data1.substring(1).slice(-1); // get rid of the leading and trailing '
var strings = data1.split("', '"); // split on the actual delimiter, not just the ,.
 
    
    If you wrapped the string in square brackets and replaced the single-quotes with double-quotes, you'd have a valid JSON string. At that point, JSON.parse() would turn that into an actual array.
var obj = { data1: "'opt1', 'opt2', 'opt3'", data2: "plaintext"};
var strData = "[" + obj.data1.replace(/'/g, "\"") + "]";
var arrData = JSON.parse(strData);
console.log(arrData);Or using template literals...
var obj = { data1: "'opt1', 'opt2', 'opt3'", data2: "plaintext"};
var strData = `[${obj.data1.replace(/'/g, "\"")}]`;
var arrData = JSON.parse(strData);
console.log(arrData);The only reason I suggest this over the standard split("', '") is in the event your data comes back without spaces in it (data1: "'opt1','opt2','opt3'"), the parse would still work, whereas split would not (unless you did a similar replace to that above and removed the spaces to be safe).
That said, if this isn't a possible scenario, either method would work.
 
    
    const obj = {data1: "'opt1', 'opt2', 'opt3'", data2: "plaintext"}    
const array = obj.data1.replace(/'/g,'').split(', ')
console.log(array) 
    
    If your datasource is reliable, you might use eval.
If not reliable, check the data first.
var d = { data1: "'opt1', 'op,t2', 'op\\'t3'", data2: "plaintext"};
d.data1 = eval(`[${d.data1}]`);
console.log(d);But the best solution would be to fix the datasource as @JohnMontgomery suggested.
