0

I am having a variable which stores a string like this

var colorArr="['#3f67c5', '#cb4728', '#f19d39', '#459331', '#984830', '#8C2094']"

I am trying to convert this string into an array by

var result = JSON.parse(colorArr)

But I keep on getting the following error "SyntaxError: Unexpected token ' in JSON at position 1

Is there a way by which I can convert this string into a proper array?

Thanks in advance

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Meet
  • 15
  • 5
  • 2
    Your string is not a valid JSON. You must use double quotes in JSON: `var colorArr = '["#3f67c5", "#cb4728", ...]'`. – kaveh Jul 29 '20 at 16:07
  • @kaveh Thanks...yup it worked – Meet Jul 29 '20 at 16:11
  • Check out this answer: https://stackoverflow.com/questions/36038454/parsing-string-as-json-with-single-quotes JSON standard requires double quotes – alonexatlast Jul 29 '20 at 16:12

3 Answers3

0

Use single quotes and put double quotes inside of it

var colorArr= '["#3f67c5", "#cb4728", "#f19d39", "#459331", "#984830", "#8C2094"]';

var result = JSON.parse(colorArr)

console.log(result)
xMayank
  • 1,875
  • 2
  • 5
  • 19
0

You can use regex to replace and split.

let colorArr="['#3f67c5', '#cb4728', '#f19d39', '#459331', '#984830', '#8C2094']";
let myArray = colorArr.replace(/'/g,'"')
console.log(JSON.parse(myArray))
Talg123
  • 1,468
  • 1
  • 10
  • 15
0

try like this

var colorArr='["#3f67c5", "#cb4728", "#f19d39", "#459331", "#984830", "#8C2094"]';
JSON.parse(colorArr)
Mahmod Abu Jehad
  • 167
  • 2
  • 14