简体   繁体   English

是否有正确的方法来解析JavaScript中以循环开头的JSON?

[英]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. 我知道我可以使用jQuery和其他库轻松处理此问题,但我想亲自了解处理这些响应的最佳方法。 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. 我知道一个很常见的实现是利用while循环的前置,可以使用.replace(/^while\\(\\d*\\);/, '') ,但这感觉像是一种粗略而骇人的方式处理它,它仅说明一种可能的变化。

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) . 或更不通用的.slice(9) Servers don't prepend arbitrary or even dynamically generated loops, they use the shortest/simplest possible one to prevent JSON hijacking . 服务器不添加任何甚至是动态生成的循环,它们使用最短/最简单的循环来防止JSON劫持 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); 除了replace() ,另一种方法是使用slice()前9个字符,因为while(1); has 9 characters, so you can discard it and use JSON.parse() to make it object from string. 9个字符,因此您可以丢弃它并使用JSON.parse()使其成为字符串对象。

 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))); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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