4

If I have this below as a string, how can I easily make that into an array?

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

I want the same result as:

var x = [[0.01,4.99,0.01],[5,14.95,0.05]];
Erwin
  • 4,757
  • 3
  • 31
  • 41
badtant
  • 163
  • 1
  • 12

2 Answers2

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

Or the way jQuery does JSON parsing (better than eval):

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

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

Prinzhorn
  • 22,120
  • 7
  • 61
  • 65
5
var x = JSON.parse("[[0.01,4.99,0.01],[5,14.95,0.05]]");

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

Andras Zoltan
  • 41,961
  • 13
  • 104
  • 160
  • +1 for mentioning json2.js. Related: http://stackoverflow.com/questions/891299/browser-native-json-support-window-json – kapa Sep 25 '12 at 09:54
  • 2
    As a side note, you might be tempted to use eval() instead of JSON.parse for browsers that do not have JSON defined, but do NOT. Use Corckford's js to make it work. – Salketer Sep 25 '12 at 09:54