m_p m_p - 5 months ago 29
Javascript Question

Strip out while(1) prepended to JSON object

I am making an ajax get request, but receive back a JSON object prepended with while(1) eg.

while(1);{"servers":[{"some_data": data, "etc":...}]}


We just started doing this to prevent malicious attacks, but I am not sure how to strip it out so that I can parse the JSON properly.

here is the function I am using for the $.get call

function myFunction() {
$.get('/v1/servers').success(function(data) {
data.servers.forEach(function(server){
presentServer(server);
});
});
}

Answer

Try this:

var text = ajaxResponse.responseText;
var jsonObject = JSON.parse(text.replace('while(1);', ''));

Another way without using replace:

var jsonObject = JSON.parse(text.substring(text.indexOf(';') + 1);

Updated with your function:

function myFunction() {
    $.get('/v1/servers').success(function(response) {
      var data = JSON.parse(response.responseText.substring(text.indexOf(';') + 1));
      data.servers.forEach(function(server){
        presentServer(server);
      });
    });
}
Comments