Search code examples
javascriptnode.jsjsonnode-fetch

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

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

Solution

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