猿问

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

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


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


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


现在我在做


fetch(jsonURL)

  .then(res => {

    console.log(res); 

  });

通常我会在,console.log但我收到以下错误:


the-myth-of-the-genius-programmer-9381a884591e:1 Uncaught (in promise) SyntaxError: Unexpected token ] in JSON at position 0


长风秋雁
浏览 118回答 1
1回答

精慕HU

您需要调用response.text()以获取响应的原始文本,因此您可以在开头删除无关的内容。然后你必须自己解析JSON,你不能使用res.json().fetch(jsonURL)&nbsp; .then(res => res.text())&nbsp; .then(text => {&nbsp; &nbsp; text = text.replace('])}while(1);</x>', '');&nbsp; &nbsp; let obj = JSON.parse(text);&nbsp; &nbsp; console.log(obj);|);这假设无关的东西只是在开始时。如果 JSON 之后还有其他内容,您也需要将其删除。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答