-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?

1

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

Comments

0
var string = "[1, 2, 3, 4]";
JSON.parse(string);

Comments

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]')

8 Comments

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 no, it isn't. Also I don't get why this answer is necessary.
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
@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 both ... ...
|
0

Try this:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.