I fetch the data from an Api (Free Advice Api ) after fetching i convert the data into json format . but when I try to parse Json it through an error
VM3787:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at index.js:24:18
My JS code
let url = ` https://api.adviceslip.com/advice`;
let convert = async() =>
{
try{
let takedata = await fetch(url).then(res => res.json()).then(data => {
console.log("Api fetched Successfully");
// console.log(data);
})
return takedata;
}
catch(e)
{
console.log(e);
}
}
// console.log(convert());//this provide data in console as Json format
//converting json into array
console.log(JSON.parse(convert()));
you need to understand a bit more about promises takedata variable here is a promise not the data itself so you cannot do a json.parse on it,
so wait for that promise to return a data and do a json.parse on the data from the promise and not the promise itself
let url = ` https://api.adviceslip.com/advice`;
const fetch = require('node-fetch');
let convert = async () => {
try {
let takedata = await fetch(url);
let data = await takedata.json();
return data;
}
catch (e) {
console.log(e);
}
}
// console.log(convert());//this provide data in console as Json format
//converting json into array
console.log(convert().then(data => console.log(data)));
Also res.json() already returns an object and JSON.parse needs a string to parse not an object.
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.