繁体   English   中英

如何在javascript中格式化JSON输出

[英]How can I format JSON output in 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.source )的( object.text )。

在响应上使用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));
}

您可以以这种方式直接使用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)
});

};

您可以使用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)
});

};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM