Turn string into array?

If I have it below as a string, how can I easily do this in an array?

"[[0.01,4.99,0.01],[5,14.95,0.05]]" 

I need the same result:

 var x = [[0.01,4.99,0.01],[5,14.95,0.05]]; 
+4
source share
2 answers
 var x = JSON.parse("[[0.01,4.99,0.01],[5,14.95,0.05]]"); 

Or the way jQuery handles JSON (better than eval ):

 var x = (new Function("return " + "[[0.01,4.99,0.01],[5,14.95,0.05]]"))(); 

To complete this answer, you can use polyfill for older browsers to support JSON.parse and JSON.stringify . I recommend json3 because Crockfords json2 is owned by crockfordy (insiders know what I mean).

+9
source
 var x = JSON.parse("[[0.01,4.99,0.01],[5,14.95,0.05]]"); 

For older browsers that don't have a built-in JSON object, you can download Crockford json2.js , which defines a JSON object with the same API, if it is not already defined.

+5
source

Source: https://habr.com/ru/post/1436114/


All Articles