Search code examples
javascriptfetch-apicloud9

Parse API response with JavaScript


I have got the response from the JSON API, but I don't know how to parse it, it just comes back with an error, I don't know enough about it to figure it out, it returns:

(node:36308) UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token o in JSON at position 1

var fetch = require('node-fetch');
fetch('https://sv443.net/jokeapi/v2/joke/Any', function(res){
    if (res.ok) {
        return res;
        } else {
        console.log(res.statusText);
    }
})
.then(res => res.json())
.then((json) => {
    var parsedData = JSON.parse(json)
    console.log(parsedData.joke);
});

Solution

  • You just need to do the following to access the delivery.

    fetch("https://sv443.net/jokeapi/v2/joke/Any?type=single")
      .then(response => {
        return response.json();
      })
      .then(json => {
        // likely to be json.delivery but cannot 
        // confirm until rate limits have been lifted
        console.log(JSON.stringify(json));
      })
      .catch(err => {
        console.log(err);
      });