如何加载JSON和拆分响应字符串?

Zac*_*iro 0 javascript json

我有一个返回JSON的网址,但返回字符串的开头是

])}while(1);</x>{"success":true,"payload":{"value":

我想拆分])}while(1);</x>并查看该split数组的[1]值。

现在我在做

fetch(jsonURL)
  .then(res => {
    console.log(res); 
  });
Run Code Online (Sandbox Code Playgroud)

通常情况下,我会在处分裂,console.log但遇到以下错误:

天才程序员的神话9381a884591e:1未捕获(承诺)SyntaxError:JSON中位置0处的意外令牌]

Bar*_*mar 5

您需要致电response.text()以获取响应的原始文本,因此您可以在开始时删除多余的内容。然后,您必须自己解析JSON,不能使用res.json()

fetch(jsonURL)
  .then(res => res.text())
  .then(text => {
    text = text.replace('])}while(1);</x>', '');
    let obj = JSON.parse(text);
    console.log(obj);
|);
Run Code Online (Sandbox Code Playgroud)

假设无关紧要的东西只是开始。如果JSON之后还有其他内容,则也需要将其删除。