Home > Blockchain >  Converting Nodejs function return to JSON data
Converting Nodejs function return to JSON data

Time:01-26

I am working on a Nodejs project which is previously done. Now, I would like to check if the returning data is in JSON or not? if not, how can I convert it. Basically, I am trying to modify a search result in Nodejs and call the node api in React client. FYI, this project deals with huge data set.

Thank you in advance for your help.

CodePudding user response:

Use the axios package to fetch the data from the backend. You can also use the built in fetch method on the frontend and then use .json() to convert it.

CodePudding user response:

Try this function

function isJson(input) {
    try { 
        let result = JSON.parse(input);
        return result; 
    } catch(e) { 
        return false;
    }
}

When trying to parse an input that isn't JSON, it will throw an error, that's why the try and catch, if there's an error, that means it couldn't be parsed, then it's not JSON and the function will return false, if it is JSON, will return the parsed input

Have a nice day :D

  •  Tags:  
  • Related