-1

This might be a dumb question but I have a string like so:

"[1, 2, 3, 4]"

I want to convert it into an actual array:

[1, 2, 3, 4]

How do I go about this?

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
  • 4
    `JSON.parse("[1, 2, 3, 4]")` - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse – Nick Parsons Mar 07 '19 at 14:41

4 Answers4

3

Just JSON parse it! JSON.parse("[1, 2, 3, 4]")

Tom Finney
  • 2,670
  • 18
  • 12
0
var string = "[1, 2, 3, 4]";
JSON.parse(string);
Ashishya11
  • 51
  • 4
0

You should use AND validate Tom Finney's or Ashishya11's or Hasee Amarathunga's answer because mine contains a gross security vulnerability if your string input comes from an untrusted source. But anyways, you can also do it like this:

const array = eval('[1, 2, 3, 4]')
Hammerbot
  • 15,696
  • 9
  • 61
  • 103
  • 1
    or an alternative to eval, a function constructor: `const array = Function("return [1, 2, 3, 4]")()` - which apparently is supposed to be _less_ of a security threat, but can still be harmful – Nick Parsons Mar 07 '19 at 14:48
  • @nick no, it isn't. Also I don't get why this answer is necessary. – Jonas Wilms Mar 07 '19 at 14:56
  • This answer is not *necessary*, I was just pointing out the fact that this is a solution to OP's question after 3 exact same solutions provided as answers. I can delete it if you find it harmful – Hammerbot Mar 07 '19 at 14:58
  • @JonasWilms when you say “it isn’t” do you mean that it isn’t an alternative to eval or that it isn’t less of a security threat? – Nick Parsons Mar 07 '19 at 15:03
  • @nick both ... ... – Jonas Wilms Mar 07 '19 at 15:04
  • @JonasWilms The reason that I thought it is is because of: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval under the “do not use eval” section it mentions that a better alternative is to use a function constructor – Nick Parsons Mar 07 '19 at 15:07
  • @JonasWilms so after reading that I don’t understand why “it isn’t”? – Nick Parsons Mar 08 '19 at 01:26
  • @nick well yes, the code executed via Function is not executed in the current scope ... but there are rarely cases where you'd use `eval` in an evil maner to extract variables. I guess it is mostly used for cross site scripting attacks, and then the attacker probably manipulates the DOM, which works with `eval` and `Function` (never seen those attacks in the wild though) – Jonas Wilms Mar 08 '19 at 07:43
  • @JonasWilms I see, thanks – Nick Parsons Mar 08 '19 at 07:55
0

Try this:

JSON.parse("[1, 2, 3, 4]")
Hasee Amarathunga
  • 1,901
  • 12
  • 17