简体   繁体   English

在使用 node-fetch 解析为 JSON 之前替换原始数据中的字符

[英]Replace character in raw data before parsing to JSON using node-fetch

I'm trying to fetch raw data from a website and convert it into JSON, but the problem is that the data uses single quotes instead of double quotes, which gives an error我正在尝试从网站获取原始数据并将其转换为 JSON,但问题是数据使用单引号而不是双引号,这会产生错误

UnhandledPromiseRejectionWarning: FetchError: invalid json response body at (WEBSITE_LINK) reason: Unexpected token ' in JSON at position 1 UnhandledPromiseRejectionWarning: FetchError: invalid json response body at (WEBSITE_LINK) reason: Unexpected token ' in JSON at position 1

If I open the page in my browser, this is what the data looks like: {'test': True, 'number': 0}如果我在浏览器中打开页面,数据如下所示: {'test': True, 'number': 0}

How can I convert the single quotes to double quotes before parsing it into JSON using the following code?在使用以下代码将单引号解析为 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)
    });

You can use the js String replace method ad parse the returning sting manually.您可以使用 js 字符串替换方法 ad 手动解析返回的字符串。

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

Use the String constructor to convert the response to a string and then apply the replace method.使用String构造函数将响应转换为字符串,然后应用替换方法。

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

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

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