0

Is it possible to turn this:

var a = "[0,0,1,1,0,0,1,[1,0,2]]";

into an array so it will work with this?

var newArray = a; // now newArray is [0,0,1,1,0,0,1,[1,0,2]], not "[0,0,1,1,0,0,1,[1,0,2]]"
3
  • 4
    JSON.parse()? Commented Dec 5, 2016 at 21:56
  • 1
    JSON.parse(a) Commented Dec 5, 2016 at 21:56
  • 2
    JSON.parse Edit: Oh... Well, I think you got your answer haha. Commented Dec 5, 2016 at 21:56

5 Answers 5

5
var a = "[0,0,1,1,0,0,1,[1,0,2]]";
var result = JSON.parse( a );
Sign up to request clarification or add additional context in comments.

1 Comment

Oh ok, that works. But i have an array with a variable name in it, a, and the parse doesn't work with strings or variables, does it?
0
var newArray = JSON.parse(a)

That will convert from string to array.

Comments

0

In addition to JSON.parse you could use eval:

var a = "[0,0,1,1,0,0,1,[1,0,2]]";
var newArray = eval(a);

As for a discussion on whether to use JSON.parse or eval, see this SO discussion: JSON.parse vs. eval()

8 Comments

There is no discussion. Never use eval();
@ScottMarcus Never is such a strong word. It should be an absolute last resort and can be useful when creating a service like JSFiddle or some other kind of code playground. But it's almost always the wrong solution.
@MikeC I don't believe there is any use case that requires eval(). Most often it requires rethinking the problem. I'll stand by never.
@ScottMarcus Again, if you're building an app with the intent of letting the user run custom Javascript then it's the right tool for the job. You don't gain anything by writing your own JS interpreter.
@Mike C I would not use eval() even in that situation. There are always other options besides eval().
|
0

Yes, it is possible, these browsers support JSON.parse(), which will parse a given String and converts it into an object, if the given string is a valid JSON representation.

Comments

0

Also you can do:

var result = eval("[0,0,1,1,0,0,1,[1,0,2]]");

You result will be:

[0, 0, 1, 1, 0, 0, 1, Array[3]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.