Problem parsing large json using eval and alternative
I'm trying to parse a large json file (240'000 chars) using javascript. I'm using ajax to retrieve json data from a servlet. The code I'm using works fine with smaller samples but just throws this out when xmlHttp.responseText contains a lot of json data.
Uncaught SyntaxError: Unexpected token ILLEGAL
mycallbackFunction
xmlHttp.onread开发者_运维知识库ystatechange
It says that the unexpected token is on the line containing
var data = eval('(' + xmlHttp.responseText + ')');
This is the gist of the code:
getJsonData(mycallbackFunction, parameters);
function getJsonData(callbackFunction, parameters){
var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', servlet_url + parameters, true);
xmlHttp.onreadystatechange = function(){
callbackFunction(xmlHttp);
}
xmlHttp.setRequestHeader('Content-Type', 'application/json');
xmlHttp.send(null);
}
function mycallbackFunction(xmlHttp){
var data = eval('(' + xmlHttp.responseText + ')');
}
The method that uses eval() is called from xmlHttp.onreadystatechange if that makes any difference.
I also tried using json2.js and a get the same result, it works fine with smaller json samples but when I try with my 240k chars file it says:
Uncaught #<Object>
Thanks in advance.
You should use
var data = JSON.parse( xmlHttp.responseText );
To ensure a JSON parser is available in browsers which do not provide one (cough IE cough), you should include Douglas Crockford's json2.js on your page ahead of other scripts.
If the parser errors on your data, you should validate the JSON for problems via something like http://jsonlint.com/ . If you need, you should break your data down into smaller chunks for the validation site.
Also, to be sure your JSON is valid, you should be using a proper JSON serialization method at the server, rather than "manually" outputting via echos, prints, etc.
精彩评论