RhodosCoder RhodosCoder - 1 month ago 12
Javascript Question

How can I format JSON output in javascript

I have this function that fetches a JSON object .

function dataFetch(){
const url = "http://www.quotzzy.co/api/quote?key=436587";

fetch(url)
.then(function(response) {
return response.text();
})
.then(function(text) {
console.log('Request successful', text);
})
.catch(function(error) {
log('Request failed', error)
});

};


How can I return the indices in the JSON object individually to use in HTML.
Like
My name(object.name) and my quote is (object.text) from this source(object.source).

Answer Source

You can directly use the json() method of the Response object in this manner.

function dataFetch(){
const url =  "http://www.quotzzy.co/api/quote?key=436587";

fetch(url)
.then(function(response) {
if(response.status == 200){
  return response.json();
})
.then(function(responseObj) {
 var text = responseObj.text;
 var authorName = responseObj.author.name;
 var source = responseObj.author.wiki;
 ...//access all attributes from the json 
 ...//assign them to HTML elements
})
.catch(function(error) {
log('Request failed', error)
});

};