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?

BadFeelingAboutThis
  • 14,445
  • 2
  • 33
  • 40
xtra
  • 69
  • 1
  • 2
  • 9

1 Answers1

4

I think you're missing the parenthesis:

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

But why not use JSON.parse??

var text = JSON.parse(mag);
frenchie
  • 51,731
  • 109
  • 304
  • 510
  • Why do the parentheses matter when including the string directly works without them? (And even the "broken" code works fine for me here: http://jsfiddle.net/HvrzK/ - tested with Chrome.) – nnnnnn Sep 11 '12 at 22:50
  • 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. – xtra Sep 11 '12 at 22:55
  • Because the a json string that starts with a curly brace "{" will make the content of the string interpreted as a statement instead of an object. Your "broken" code isn't valid json as it's not wrapped around {} so the eval works. – frenchie Sep 11 '12 at 22:55
  • JSON doesn't require `{}` to be valid - JSON supports arrays. – nnnnnn Sep 11 '12 at 22:58
  • 1
    @nnnnnn: yes, you're right arrays too. Anyway, the correct syntax is eval('(' + mag + ')') – frenchie Sep 11 '12 at 23:00
  • Frenchie I've tried with your syntax but it unfortunately doesn't work still. – xtra Sep 11 '12 at 23:04
  • 1
    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. – frenchie Sep 11 '12 at 23:26
  • 1
    @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. – Jay Sep 12 '12 at 04:06