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

1.3k Views Asked by At

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

There are 2 best solutions below

2
On BEST ANSWER

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

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