Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need to add parentheses to eval JSON? [duplicate]

Why does the following code needs to add ( and ) for eval?

var strJson = eval("(" + $("#status").val().replace(";","") + ")");

PS: $("#status").val() is returning something like {"10000048":"1","25000175":"2","25000268":"3"};

like image 328
Ricky Avatar asked Sep 29 '10 09:09

Ricky


1 Answers

It depends what the value in that element is (an unknown), wrapping it in () is the safe route to account for possibly of no input being there.

Edit: Now that you've cleared up it's JSON, this isn't valid:

eval('{"10000048":"1","25000175":"2","25000268":"3"}');

But this will result in a valid object being returned:

eval('({"10000048":"1","25000175":"2","25000268":"3"})');
//effectively:
eval('return {"10000048":"1","25000175":"2","25000268":"3"};');

Picture in a JavaScript file:

<script type="text/javascript">
  {"10000048":"1","25000175":"2","25000268":"3"}
</script>

This is going to fail, it's just an object declared inline but not proper syntax...the same reason a server has to support JSONP for it to work.


A bit tangential to the question, but since you're including jQuery, you might as well use $.parseJSON() (which will use the native JSON.parse() if available) for this:

var strJson = $.parseJSON($("#status").val().replace(";",""));
like image 167
Nick Craver Avatar answered Oct 11 '22 05:10

Nick Craver