最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript Fetch api [object object] - Stack Overflow

programmeradmin2浏览0评论

Why is the code I try to run below return as [object object]?

var request = new Request('data/some.json');

  fetch(request).then(function(response) {
    return response.json();
  }).then(function(json) {
      document.getElementById("test").innerHTML = json.items;
  });

Why is the code I try to run below return as [object object]?

var request = new Request('data/some.json');

  fetch(request).then(function(response) {
    return response.json();
  }).then(function(json) {
      document.getElementById("test").innerHTML = json.items;
  });
Share Improve this question edited Nov 21, 2016 at 19:18 Raman Shrivastava 2,95316 silver badges27 bronze badges asked Nov 21, 2016 at 19:02 Emre GozelEmre Gozel 451 gold badge2 silver badges7 bronze badges 1
  • Use response.data. – Tome Pejoski Commented Nov 21, 2016 at 19:06
Add a ment  | 

2 Answers 2

Reset to default 5

document.getElementById("test").innerHTML = json.items; is the issue here.

You should do:

document.getElementById("test").innerHTML = JSON.stringify(json.items);

This is because if you try to paint a plain JavaScript object in the DOM, it'll call the object's toString function, which will result in [object object].

Most likely because your response is a JSON string representing an object, which is then parsed to a JavaScript object.

When you try to use this object as innerHTML, it is stringified via toString(), which in turn returns [object Object]:

console.log(({foo: "bar"}).toString()); // "[object Object]"


If you want to display the JSON representation of the object, simply skip the step where you parse your JSON into a JavaScript object via json() and use the plain text representation obtained via text() instead:

var request = new Request('data/some.json');

fetch(request).then(function(response) {
    return response.text();
}).then(function(text) {
    document.getElementById("test").innerHTML = text;
});
发布评论

评论列表(0)

  1. 暂无评论