0

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()));
VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • `this provide data in console as Json format` when it's already in parsed json format, why do you want to parse it again ? – Code Maniac May 22 '22 at 05:56
  • `convert()` is 1. an async function 2. returns an object already. You get an error because of 1. - you're trying to parse the promise that the async function returns as JSON. Even if you were to [get the value the promise would give you](https://stackoverflow.com/questions/29516390/how-to-access-the-value-of-a-promise) you'd still get an error as you'd be parsing data that's already parsed. That's what `res.json()` does. – VLAZ May 22 '22 at 05:56

1 Answers1

0

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.

Srinjoy Choudhury
  • 622
  • 1
  • 4
  • 19