1

I have an array of objects that's being passed as a string. I would expect eval to be able to evaluate this into an the real array object, but

var arr = '"[{item:1,amount:100,quantity:1},{item:2,amount:200,quantity:2}]"';
console.log(eval(arr));

just returns what seems to be a string. Am I using it incorrectly?

1252748
  • 14,597
  • 32
  • 109
  • 229

1 Answers1

2

You'll have to do a double eval to get the data as an array

var arr = '"[{item:1,amount:100,quantity:1},{item:2,amount:200,quantity:2}]"';
console.log(eval(eval(arr)));
Musa
  • 96,336
  • 17
  • 118
  • 137
  • You even might do `JSON.parse()` in the inner call :-) – Bergi Oct 22 '13 at 17:57
  • *Why is this* Because you have a string inside of the string as the comments above said. Drop the outer quotes and use `JSON.parse()` and tada, it works. – epascarello Oct 22 '13 at 18:00
  • 1
    @thomas What you have in arr is a string holding a js string literal, when you eval it you get the string, this string contains a js array literal when you eval that you get the array. – Musa Oct 22 '13 at 18:00
  • @Bergi why would that be preferable? – 1252748 Oct 22 '13 at 18:03
  • 2
    @epascarello When I do that I get a syntax error: `"Unexpected token i"` – 1252748 Oct 22 '13 at 18:05
  • @thomas: Less [`eval`-evilness](http://stackoverflow.com/questions/197769/when-is-javascripts-eval-not-evil) :-) It's not really preferable, you should just use proper [JSON](http://json.org/) – Bergi Oct 22 '13 at 18:10
  • @Bergi aye, yeah, but I don't have control over how this data is passed to me. I have to make due. Is there a way to change it to JSON without eval, given just this string? – 1252748 Oct 22 '13 at 18:13
  • @thomas: You need to wrap the inner string in parentheses to prevent it from being parsed as a blog. – SLaks Oct 22 '13 at 18:27