views:

142

answers:

3

I have a very large JSON string that I need to parse with in-browser JavaScript. Right now, in a few browsers, I run out of stack space. Unfortunately, my JSON can contain user strings, so I can't use eval or otherwise let the browser parse it.

I've looked at a few of the standard JavaScript JSON parsers, and they are recursive. Wondering if anyone knows of any JSON parser that is safe and non-recursive. I'd be willing for it to have fewer features -- I just have a giant array of objects.

Alternatively, if someone knows of one that might be easy to modify, that would be a big help too.

EDIT: On closer inspection the stack overflow is thrown by eval() used inside the parser. So, it must be recursive.

+1  A: 

JSON parsing in browser is usually done with just eval, but preceding the eval with a regular expression "lint", that is supposed to make it safe to evaluate the JSON.

There is an example on this on wikipedia:

Nakedible
right, I see now that eval is being called after checking for safety, and then it throws a stack overflow (because it's internally recursive and the JSON string is large)
Lou Franco
Thanks -- your suggestion helped me see the real problem was in eval().
Lou Franco
+4  A: 

If eval throws stackoverflow, you can use this

http://code.google.com/p/json-sans-eval/

A JSON parser that doesn't use eval() at all.

Lou Franco
+1  A: 

Hi, I recommend you to divide JSON string in chunks, and bring them on demand. May be using AJAX too, you can have a recipe that just fit your needs. Using a "divide and conquer" mechanism, I think you can still use common JSON parsing methods.

Hope that helps,

Ramon Araujo
We considered that, but it's difficult given other constraints. We need to send the response all at once. To delimit it so that a split() would work requires another escaping pass. We might still go this way, but hoping to find a better parser.
Lou Franco