如何在javascript中格式化JSON输出

时间:2017-07-02 18:00:45

标签: javascript json

我有这个函数来获取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)。

3 个答案:

答案 0 :(得分: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));
}

答案 1 :(得分: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)
});

};

答案 2 :(得分: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)
});

};