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
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}
How can I convert the single quotes to double quotes before parsing it into JSON using the following code?
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.
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.
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) });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.