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
2 Answers
Reset to default 5document.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;
});