2017-07-02 138 views
1

我有這個函數可以獲取JSON對象。如何在javascript中格式化JSON輸出

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) 
    }); 
}; 

如何返回單獨的JSON對象中的索引以在HTML中使用?

贊,我的名字(object.name)和我的報價是(object.text)從這個信息源(object.source)。

+1

'JSON.parse'和'JSON.stringify'可用於串和JSON格式之間隱蔽。您可以閱讀response.text(),然後閱讀感興趣的特定屬性。 –

+0

我已經使用了這兩個,我更喜歡JSON.parse();但我如何提取該數據在HTML中使用,我試過沒有成功的循環,我得到了未定義。 – RhodosCoder

+0

你的問題相當廣泛。您能否提供一個具體的數據示例,以及您想要在HTML中產生的結果? (編輯你的問題) – trincot

回答

1

您可以以這種方式直接使用Response對象的json()方法。

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) 
}); 

}; 
+0

謝謝@torazaburo指出。 –

0

您可以使用response.json()爲JSON對象的響應轉換。 response.json()方法返回一個promise。您將解決承諾,您可以獲得JSON對象。

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) 
}); 

}; 
2

使用json()的響應。它返回對象的承諾。

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) 
    }); 
} 

更多慣用:

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)); 
} 
+0

json.name返回'undefined' – RhodosCoder

+1

@RodosCoder,因爲'json.name'不是一個屬性。 'json.author.name'是。一旦擁有了JSON,就可以像讀取任何其他JSON一樣從它讀取屬性。 –

+0

torazaburo我愛那個ES6的語法:) – RhodosCoder