'Converting Nodejs function return to JSON data
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.
Solution 1:[1]
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.
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sean Lawton |
| Solution 2 | Asterki |
