Abhisar Tripathi
Abhisar Tripathi

Reputation: 1659

How to convert this string to a javascript array?

I am getting this error when I try to JSON.parse this string "['Answer 1', 'Answer 2']"

Uncaught SyntaxError: Unexpected token ' in JSON at position 1
    at Object.parse (<anonymous>)
    at <anonymous>:1:6

Can anybody tell me how to do it?

Upvotes: 0

Views: 29

Answers (1)

Derek Wang
Derek Wang

Reputation: 10194

You need to replace all single quote(') into double quote(") to parse to javascript array.

const input = "['Answer 1', 'Answer 2']";
const output = JSON.parse(input.replaceAll("'", '"'));
console.log(output);

Upvotes: 2

Related Questions