使用node-fetch

问题描述

我正在尝试从网站获取原始数据并将其转换为JSON,但是问题是数据使用单引号而不是双引号,这会导致错误

UnhandledPromiseRejectionWarning:FetchError:(WEBSITE_LINK)处的json响应正文无效,原因:位置1的JSON中出现意外令牌'

如果在浏览器中打开页面,则数据如下所示: {'test': True,'number': 0}

在使用以下代码将其解析为JSON之前,如何将单引号转换为双引号?

let url = `WEBSITE_LINK`;
let settings = { method: "Get" };
fetch(url,settings)
   .then(res => res.json())
   .then((json) => {
         console.log(json.test)
         console.log(json.number)
    });

解决方法

您可以使用js字符串replace方法来手动解析返回的字符串。

let url = `WEBSITE_LINK`;
let settings = { method: "Get" };
fetch(url,settings)
   .then(res => res.text())
   .then((text) => {
         const json = JSON.parse(text.replace(/'/g,'"'));
         console.log(json.test);
         console.log(json.number);
    });
,

使用 String 构造函数将响应转换为字符串,然后应用replace方法。

let url = `WEBSITE_LINK`;
let settings = {
  method: "Get"
};
fetch(url,settings)
  .then(res => {
    const text = String(res.text()).replace(/'/g,'"');
    return JSON.parse(text);
  })
  .then((json) => {
    console.log(json.test)
    console.log(json.number)
  });