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).
Antti29
3,03912 gold badges37 silver badges36 bronze badges
3 Answers 3
Use json() on the response. It returns a promise for the object.
function dataFetch(){
const url = "http://www.quotzzy.co/api/quote?key=436587";
fetch(url)
.then(function(response) {
return response.json();
})
.then(function(json) {
console.log(json.author.name);
});
.catch(function(error) {
log('Request failed', error)
});
}
More idiomatic:
function dataFetch(){
const url = "http://www.quotzzy.co/api/quote?key=436587";
fetch(url)
.then(response => response.json())
.then(json => console.log(json.author.name, "said", json.text))
.catch(error => log('Request failed', error));
}
Sign up to request clarification or add additional context in comments.
4 Comments
RhodosCoder
json.name returns
undefinedRajeev Ranjan
@RhodosCoder , its because
json.name is not an attribute. json.author.name is. Once you have the JSON, you can read properties from it like any other JSON.RhodosCoder
torazaburo I do love that ES6 syntax :)
RhodosCoder
@RajeevRanjan SOLVED IT, thanks so much , off course I knew object notation but couldn't figure that out.
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)
});
};
answered Jul 2, 2017 at 18:30
Rajeev Ranjan
4,1867 gold badges34 silver badges59 bronze badges
Comments
You can use response.json() to convert your response as JSON object. The response.json() method returns a promise. You will resolve promise you can get JSON object.
function dataFetch(){
const url = "http://www.quotzzy.co/api/quote?key=436587";
fetch(url)
.then(function(response) {
// return response.text(); // wrong
return response.json(); // right
})
.then(function(json) {
console.log('Request successful', json);
})
.catch(function(error) {
log('Request failed', error)
});
};
answered Jul 2, 2017 at 18:32
Vasi
1,2271 gold badge10 silver badges18 bronze badges
Comments
lang-js
JSON.parseandJSON.stringifycan be used to covert between string and JSON formats. You can read the response.text() and then the specific attribute of interest.