Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an array in string format to javascript array

I have an array which is in string format,

var str = { 
    id: 123,
    changes: "[[atr:test1, old:null, new:null], [atr:messageText, old:test here, new:hello test], [atr:status, old:null, new:1]]"
}
var d = str.changes

I tried to convert the 'changes' array from string format using different methods by combining split(), replace(), slice() etc...and even JSON.parse(), but nothing worked.

Is there any way to convert this into javascript array?

like image 734
NEETHU VIJAYAN Avatar asked Aug 02 '26 21:08

NEETHU VIJAYAN


1 Answers

Note that the string is not valid anything but string. It is not a valid array, and the string is not valid JSON.

If you can, get the server to change it to the valid JSON string

"[{\"atr\":\"test1\", \"old\":null, \"new\":null}, {\"atr\":\"messageText\", \"old\":\"test here\", \"new\":\"hello test\"}, {\"atr\":\"status\", \"old\":null, \"new\":1}]"

If the response is ALWAYS on the format you gave, then you can create valid JSON

var str = {
  id: 123,
  changes: "[[atr:test1, old:null, new:null], [atr:messageText, old:test here, new:hello test], [atr:status, old:null, new:1]]"
}

// change the inner [ ] to { }
let changes = str.changes.replace(/\[\[/g, "[{").replace(/\], \[/g, "},{").replace(/\]\]/g, "}]")

// change the unquoted keys and values to quoted keys and values
changes = changes.replace(/(\w+):/g, '"$1":').replace(/:([\w ]+)([},])/g, ':"$1"$2')

// parse the object
changes = JSON.parse(changes);

// replace "null" with null - could have been done above bt the regex would be nasty
changes.forEach(item => Object.keys(item).forEach(key => item[key] = item[key] === "null" ? null : item[key]))

console.log(changes)
like image 66
mplungjan Avatar answered Aug 05 '26 09:08

mplungjan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!