2

Is there some javascript function that can take a string already formatted as an array, and casts it as an array?

var some_string = "[1,2,3,4]";
var some_array = castAsArray(some_string);
some_array.length // Returns 4.
7
  • It's valid JSON, so var some_array = JSON.parse(some_string);. If the actual string isn't JSON data, then a different approach will be needed. Commented May 19, 2014 at 16:54
  • You could use the evil eval :P Commented May 19, 2014 at 16:55
  • @Loktar I was thinking eval too, but then I sacrificed my car to Satan and all was well. Commented May 19, 2014 at 16:56
  • 3
    @DonnyP stackoverflow.com/questions/86513/… Commented May 19, 2014 at 16:59
  • 1
    However if he is controlling his input, the only thing he would have to contend with is performance. Commented May 19, 2014 at 17:00

2 Answers 2

10

What you're looking for is JSON.parse(). It'll take any string that represents a valid JavaScript object in JSON (JavaScript Object Notation), and convert it to an object.

var some_string = "[1,2,3,4]";
var some_array = JSON.parse(some_string);
some_array.length // Returns 4.
Sign up to request clarification or add additional context in comments.

1 Comment

Life can be simple sometimes ...
1

Even eval will do the trick. Using eval, is not good practice but it is just a suggestion.

a="[1,2,3,4]"
b=eval(a)

Understand that using eval is always a bad idea (always means at most of the cases) and this is one excellent SO question and answers discussing this.

Eval-Don't use it.

16 Comments

If you are going to downvote, leave a comment please. He is trying to help. @Shmiddty, it's great that you know why this is wrong, but at some point you didn't. Instead of "tsks", please explain why.
+1 It's a valid solution, and could be the best solution in some cases.
@Jack_of_All_Trades I didn't downvote, but just because it works, doesn't mean it's good code. Typically there is no justifiable reason to use eval like this. Answers should provide good code, not "suggestions"
The downvote isn't mine but it's likely because JSON.parse() is the actual way to do this, and using eval() in this case accomplishes nothing but opening you up to exploits.
@sphanley: That's an overreaction to eval. JSON.parse isn't "the actual way". It's one if a number of different ways. The best way to do it will depend on the overall circumstance.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.