How to parse an array inside a string into a javascript arrray

Viewed 28

I have a string received from a database call as follows:

"[{'url':'https://www.example.com/','category':'popular'},{'url':'https://example2.com/','category':'new'}]"

I would like to parse the string into a typescript/JS array so that it is as follows:

[
   {'url':'https://www.example.com/','category':'popular'}, 
   {'url':'https://example2.com/','category':'new'}
]

How can I go about doing this? JSON.parse won't work as the string does not resemble a stringified JSON. Thanks!

2 Answers

Assuming there are no strings in it containing ', you can replace all occurrences of the single quote with double quotes, then you can parse it:

const str = "[{'url':'https://www.example.com/','category':'popular'},{'url':'https://example2.com/','category':'new'}]";

const arr = JSON.parse(str.replace(/'/g,'"'));

console.log(arr);

Replace single quotes with double quotes then JSON.parse

JSON.parse(
"[{'url':'https://www.example.com/','category':'popular'},{'url':'https://example2.com/','category':'new'}]"
.replace(/\'/g, '"')
)
Related