1

My code snippet:

function receive(mag)
{
    var text = eval(mag);
    alert(text);
}

receive('["magnolia,", ["Magnolia (Flower)"], [], [], [], [], [], [[3, 19019, "INV_MAG_39 ", 5]]]');

When I pass the string in the example (shown above), the eval(mag) doesn't work. But if I do it directly like this:

function receive(mag)
{
    var text = eval('["magnolia,", ["Magnolia (Flower)"], [], [], [], [], [], [[3, 19019, "INV_MAG_39 ", 5]]]');
    alert(text);
}

It does work. Does anyone have an idea whats wrong / how can I get it working with passed variable?

8
  • 3
    What does "won't work" mean? What actually happens with the first version? (Do you get any errors in the console?) Commented Sep 11, 2012 at 22:43
  • 1
    No really, stop using eval(). Commented Sep 11, 2012 at 22:46
  • 5
    Try using JSON.parse instead of eval. Commented Sep 11, 2012 at 22:46
  • 1
    Because eval will execute anything inside the string, and since it only makes sense to eval external data, it is potentially very dangerous. Commented Sep 11, 2012 at 22:49
  • 2
    Your code works here: jsfiddle.net/HvrzK Commented Sep 11, 2012 at 22:49

1 Answer 1

4

I think you're missing the parenthesis:

eval('(' + mag + ')')

But why not use JSON.parse??

var text = JSON.parse(mag);
Sign up to request clarification or add additional context in comments.

8 Comments

Why do the parentheses matter when including the string directly works without them? (And even the "broken" code works fine for me here: jsfiddle.net/HvrzK - tested with Chrome.)
Well, i've only included like-code because the original is too long to post. But you get my point; what it does in real code is get string with ajax and pass it to a function.
@nnnnnn: yes, you're right arrays too. Anyway, the correct syntax is eval('(' + mag + ')')
What's not working? What error are you getting? The syntax is correct so if you're not getting the result you want, the problem is elsewhere.
@xtra: Check the web browser's console log. It'll give you the exact cause of error on the exact string passed to the receive function. The string from your example does work, so it's likely that the error occured on a different string.
|

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.