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?

4
  • 1
    Your string holds a string literal. It's doing exactly what you told it to. Commented Oct 22, 2013 at 17:54
  • @SLaks an array object containing to objects with the properties item, amount, and quantity. Commented Oct 22, 2013 at 17:55
  • But that's not what your string holds. Your string just holds a double-quoted string. Commented Oct 22, 2013 at 17:55
  • @SLaks no control over how I receive this element. Did you mean something else? Commented Oct 22, 2013 at 18:07

1 Answer 1

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)));
Sign up to request clarification or add additional context in comments.

8 Comments

You even might do JSON.parse() in the inner call :-)
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.
@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.
@Bergi why would that be preferable?
@epascarello When I do that I get a syntax error: "Unexpected token i"
|

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.