JavaScript eval () function throwing an exception outside the stack

I recently ran into a problem: Valid JSON when passing the eval() function causes it to throw an error - "script stack space quota has been exhausted."

It is reproduced sequentially, and upon initial examination it seems that this is a limitation on the number of attributes / properties of an object that can be defined (rather than the size of the content).

Here is an example code:

 function starttest() { var d = new Array(50000); var i = 0; for (i = 0; i < d.length; i++) { d[i] = new Object(); d[i].a1 = 1; d[i].a2 = 2; d[i].a3 = i; d[i].a4 = i; d[i].a5 = i; d[i].a6 = i; d[i].a7 = i; d[i].a8 = i; d[i].a9 = i; d[i].a10 = i; d[i].a11 = i; d[i].a12 = i; d[i].a13 = i; d[i].a14 = i; d[i].a15 = i; } var jsonString = JSON.stringify(d); alert(jsonString.length); var obj = eval(jsonString); var count = 0; for( var i = 0; i< obj.length; i++) { for (var k in obj[i]) { if (obj[i].hasOwnProperty(k)) { ++count; } } } alert("Done! || Len: " + obj.length + " || " + "Attrib Count: " + count + " || " + typeof obj) } 

The funny thing is that I can define many more objects than shown in the code snippet; the problem only occurs when using the eval() function.

Any new understanding of this would be very helpful. I know that using eval() unsafe, and that’s it ... and I'm open to suggestions!

+4
source share
3 answers

Yes, this is a problem with the Firefox JavaScript interpreter in general. This is not just eval : if you put fifty thousand lines:

 {a:1,b:2,c:3,d:4,e:5,f:6,g:7,h:8,i:9,j:10,a2:1,b2:2,c2:3,d2:4,e2:5,f2:6,g2:7,h2:8,i2:9,j2:10}, 

in an array literal in a regular script or <script> file, you get exactly the same error.

The complexity of the script block seems to be limited by the compilation time of JS_DEFAULT_SCRIPT_STACK_QUOTA . See 420869 and related errors.

It is relatively unlikely that you should come across this under normal circumstances. Of course, for JSON, you can use JSON.parse , which is not a full JavaScript interpreter, independent of this limitation. If you need an invalid JSON JS parser that has not been touched, I think you will have to write it yourself ... although it will probably be annoyingly slow when you get long input.

+1
source

That means what he is saying. eval obviously uses recursion and you exceed your limit when evaluating a long and complex JSON literal. It works great with JSON.parse (at least in Firefox 3.6.11pre), which is the right tool to work with, and often faster .

+3
source

It looks like you are using the JSON class to create a JSON string. Why don't you just use the opposite function for reinforcement to return JSON to the object syntax?

http://www.json.org/json_parse.js is a JSON javsacript class. Just call json_parse (str); and you will get a good object back.

As you said yourself, eval () is not safe. This damn right evil!

+1
source

All Articles