简体   繁体   中英

Is there a proper way to parse JSON prepended with a loop in JavaScript?

I know I can use jQuery and other libraries to easily handle this, but I'd like to know personally the best way to handle these responses. I've spent extensive time searching for the proper way to handle them, but all I find is the same explanations for why they exist: anti-hijacking.

So, the title speaks for itself. I know a very common implementation utilizes the prepending of a while loop, which could be dealt with using .replace(/^while\\(\\d*\\);/, '') , but this feels like a crude and hackish way to handle it and it only accounts for one possible variation.

Is there a better way to handle it?

Trying to keep it simple, an example of this would be:

var oReq = new XMLHttpRequest();
oReq.addEventListener("load", function() {
    console.log(this.responseText);
});
oReq.open("GET", "http://www.example.org/example.json");
oReq.send();

This might produce a response like:

while(1);{"menu":{"id":"file","value":"File","popup":{"menuitem":[{"value":"New","onclick":"CreateNewDoc()"},{"value":"Open","onclick":"OpenDoc()"},{"value":"Close","onclick":"CloseDoc()"}]}}}

this feels like a crude and hackish way to handle it and it only accounts for one possible variation.

No, it's exactly what you would do. Or even less generic, .slice(9) . Servers don't prepend arbitrary or even dynamically generated loops, they use the shortest/simplest possible one to prevent JSON hijacking . So you have to deal only with that particular prefix used by the service your are requesting.

Apart from replace() , another way could be using slice() out first 9 characters because while(1); has 9 characters, so you can discard it and use JSON.parse() to make it object from string.

 const js_string = 'while(1);{"menu":{"id":"file","value":"File","popup":{"menuitem":[{"value":"New","onclick":"CreateNewDoc()"},{"value":"Open","onclick":"OpenDoc()"},{"value":"Close","onclick":"CloseDoc()"}]}}}'; //while(9); has 9 characters so remove it and parse it to json object console.log(JSON.parse(js_string.slice(9))); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM