1

In order to convert string into 1-dimensional JavaScript array I could use 'eval()'. But how to convert string into 2-dimensional array?

My string is:

['stage 1', 1, 11, 111],['Stage 2', 2, 22, 222]

Execution "eval(...)" with such parameter creates a 1 array with 4 elements: ['stage', 1, 11, 111]. Instead I would like to have array of 2 elements, where each element in turn is another array of 4 elements.

I believe, I could split original string by ',' into list of substrings and call 'eval' for each of them and combine the result into a 2-dimensional array.

But I believe that more efficient way should already exist. Is there any? If yes, please advise.

Thank you very much in advance!

1
  • Just wrap in an outer pair of braces: '[' + string + ']'. Commented Mar 25, 2013 at 5:47

1 Answer 1

3

Instead of using eval it would be better to use JSON.parse:

var string = '["stage 1", 1, 11, 111],["Stage 2", 2, 22, 222]';
var array2d = JSON.parse("[" + string + "]");
console.log(array2d);

See the demo here: http://jsfiddle.net/y94zz/

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

5 Comments

"Better" is relative, why is it better than eval? A JSON.parse shim will use eval anyway.
Why would you use eval when a much better method such as JSON.parse already exist? With eval in used, you cannot even minify your code by any standard minifier/compiler!
@RobG - All major browsers now support JSON.parse, there are shims which do not use eval (for example Crockford's own JSON-js - see json_parse.js or json_parse_state.js) and JSON.parse is much safer to use than eval since it won't execute arbitrary code nor modify variables in the calling context.
@AaditMShah—good to see an explanation. Crockford dislikes eval so much he wrote a parser, good for him. :-)
Additional thing: in the original source string the quotes for text should be double quotes, not single (as in my case). But solution helped, thanks a lot!

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.