Conversion of an "array" string to a javascript array

Asked

Viewed 133 times

0

I have a data that comes as a parameter of a function.

[['local','precipitação'],['RJ',0.2],['SP',0.8],['MG','']]

This data should be recognized as array but javascript recognizes as string. Is there any way to convert to an array?

  • Bruno, this example you gave is an array of arrays. Where is the string you want to transform into an array? If this is it, you want it to become a single array or continue to be an array of arrays?

  • If I put this direct example into a variable it works. But, if it comes from the parameter in the function it understands that it is a string. I need it read as array of arrays.

1 answer

1


To convert the string "[['local','precipitação'],['RJ',0.2],['SP',0.8],['MG','']]" in an Array you can use eval().

var s = "[['local','precipitação'],['RJ',0.2],['SP',0.8],['MG','']]";
var a = eval(s);

Some will say they use eval is bad practice, because of the risk of code injection, difficulty debugging etc.

A little better would be using JSON.parse(). However it seems that it does not accept simple quotes. In this case would be something like:

var s = '[["local","precipitação"],["RJ",0.2],["SP",0.8],["MG",""]]';
var a = JSON.parse(s);

Anyway the best would be to avoid using string unnecessarily, and pass the argument directly as Array.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.