Search code examples
javascriptasynchronousfetch

Fetch API in Javascript returning [object, object]


So i have this code here, which calls from a URL and displays the array in the console

fetch('http://jsonplaceholder.typicode.com/users') 
  .then(  
    function(response) {  
      if (response.status !== 200) {  
        console.log('Looks like there was a problem');  
        return;  
      }

      response.json().then(function(data){  
        console.log(data); 
      });  
    }  
  )  
  .catch(function(err) {  
    console.log('Fetch Error', err);  
})

However, it prints out:


[object Object] {
  address: [object Object] {
    city: "Lebsackbury",
    geo: [object Object] { ... },
    street: "Kattie Turnpike",
    suite: "Suite 198",
    zipcode: "31428-2261"
  },

Any idea on how to remove the [object, object] and have it display normally, the same as in the url??


Solution

  • Fetch doesn't return [object object]. It's working the way it should.

    What you are observing is the by-product of how console.log works on nested objects--it's using a built-in "toString()", which adds some extra information, such as the type.

    That behavior is different than how modern web browsers deal with JSON text, which is to just show it directly in the browser window in it's raw state, along with some basic formatting.

    To get what you are expecting, use console.log(JSON.stringify(data)); which will use the built in JSON stringifier. To add nicer formatting you can use console.log(JSON.stringify(data,null,2));

    However, you are taking the JSON response, parsing it into an object, then taking that object and turning it back into a JSON string. Which is pretty silly.

    Since the URL returns a JSON string, you could just console log that JSON string directly.

    Something like console.log(response.body);