3

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;
  });
1
  • Use response.data. Commented Nov 21, 2016 at 19:06

2 Answers 2

6

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].

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

If you only use text, json.items will likely be undefined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.