-1

I have a string like so :

a= "['url1','url2','url3']"

coming from the server I want to convert it to array like :

arr = ["url1","url2","url3"]

but JSON.parse does not seems to be working and gives following error:

SyntaxError: Unexpected token ' in JSON at position 1

Thanks in advance.

Salman Arshad
  • 343
  • 6
  • 23
  • 4
    In JSON, strings must be represented with double quotes. Instead of trying to find a hacky workaround, can't you fix the server to make it send valid JSON? – blex Mar 09 '20 at 20:59
  • 1
    I think you mistyped, but surely you meant `JSON.parse` rather than `JSON.stringify`? – Robin Zigmond Mar 09 '20 at 21:00
  • So what will be the valid json format for this array? – Salman Arshad Mar 09 '20 at 21:03
  • 1
    `"[\"url1\",\"url2\",\"url3\"]"` would be valid. But you should never ever ever ever try to build a JSON string yourself. Always use the built-in tools, like `json_encode` in PHP, or `JSON.stringify` in JS – blex Mar 09 '20 at 21:05
  • Does this answer your question? [Parsing string as JSON with single quotes?](https://stackoverflow.com/questions/36038454/parsing-string-as-json-with-single-quotes) – Slava Rozhnev Mar 09 '20 at 21:34

3 Answers3

0

You need to replace the single quotes with double quotes. An easy way to achieve this can be by replacing them with escaped quotes like this:

let validJSON = a.replace(/'/g, "\"")

JSON.parse(validJSON)
Martin Wahlberg
  • 113
  • 1
  • 7
0

Your string needs to be in single quotes for JSON.parse to work in this example, also string representation in json uses double quotes as per standard.


JSON.parse('["url1","url2","url3"]')

Simon Polak
  • 1,959
  • 1
  • 13
  • 21
0

Try to use this code:

a = "['url1','url2','url3']"
urls = a.split(',')
arr = urls.map(url => url.replace(/'|\[|\]/g, ''))

console.log(arr) // ["url1", "url2", "url3"]

https://jsfiddle.net/z1frh8ys/

Nick
  • 383
  • 1
  • 4
  • 16