0

I have following code in HTML part:

<script>
    var trainings = {'M':new PlayerTraining(18369,22,355),'D':new PlayerTraining(9412,6,118)};
</script>

This code works well, and 'PlayerTraining' is class defined in one of js-files referenced above.

But when I execute:

<script>
    alert(eval("{'M':new PlayerTraining(18369,22,355),'D':new PlayerTraining(9412,6,118)}"));
</script>

I receive the following error:

Uncaught SyntaxError: Unexpected token :

What am I doing wrong? In the end I need to assign that hash (received from WebService) to variable. How to do that?

Please advise.

Budda
  • 18,015
  • 33
  • 124
  • 206
  • 1
    `eval("{'M':new PlayerTraining(18369,22,355),'D':new PlayerTraining(9412,6,118)}")` is (more or less) the same as `` -> SyntaxError – Andreas Jul 20 '15 at 07:14
  • 1
    The `{` is seen as the start of a block. The following up to the closing `}` is expected to be a sequence of statements. 'M' is a string literal and `:` is a syntax error. – RobG Jul 20 '15 at 07:24

3 Answers3

1

You can't eval objects like that.

Similar to your example, this will throw a syntax error:

{ a: new Date(), b: new Date() }

This is because you're missing a variable assignment:

var x = { a: new Date(), b: new Date() }

You shouldn't be using eval in the first place, though. It's unsafe, and inefficient.

Community
  • 1
  • 1
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • I received JSON data from web service, so I consider that as efficient. Is that safe? Dunno, hope yes. See no concerns so far. – Budda Jul 21 '15 at 01:10
  • Oh, save would be to parse string... got it. Agree, thanks – Budda Jul 21 '15 at 01:12
1

To make it work you should wrap your expression in the parentheses:

alert(eval("({'M':new PlayerTraining(18369,22,355),'D':new PlayerTraining(9412,6,118)})"));

and to assign the result to a variable do it like this:

var someVar = eval("(" + webServiceResponse + ")");
Oleg
  • 22,300
  • 9
  • 68
  • 84
0

Inside eval assign your object to a var:

eval("var myVar = {'M':new PlayerTraining(18369,22,355),'D':new PlayerTraining(9412,6,118)};");
alert(myVar);

But anyway, If you have the object as string, you can parse as json.

Luca Rainone
  • 16,138
  • 2
  • 38
  • 52