card51short
card51short

Reputation: 143

My JSON output is only printing [object] instead of the values

Hey guys I'm building a local email app with Python and Javascript that uses the localhost as an API to store data.

When I'm trying to display the JSON email data on the "inbox" page, I'm just getting a bunch of [Object object]s printed out onto the page. How can I get to the values of these objects again? I'm rusty with Javascript.

I've tried just printing emails. Emails[0][index]. Emails[index][0]. I'm just getting different variations of the words "object" or "undefined".

How can I print the actual JSON values out on the page? Thanks

Thanks!

javascript:

fetch('/emails/inbox')
  .then(response => response.json())
  .then(emails => {
      
  
  for (index = 0; index < emails.length; index++) { 
    document.getElementById("emails-view").innerHTML += emails[index];
  } 

Upvotes: 0

Views: 998

Answers (2)

alex-bu-89
alex-bu-89

Reputation: 54

  • You could try formatted stringify like this:
document.getElementById("emails-view").innerHTML += JSON.stringify(emails[index], null, 4);
  • or better, if you want to know what an email object looks like, then use console.log or debugger (breakpoints).

console.log - you have to open dev tools (console tab), to see logs :)

fetch('/emails/inbox')
.then(response => response.json())
.then(emails =>
{
    for (index = 0; index < emails.length; index++)
    {
        console.log(emails[index]);
    }
}

debugger -> breakpoints:

fetch('/emails/inbox')
.then(response => response.json())
.then(emails =>
{
    debugger;
}

Upvotes: 1

N-ate
N-ate

Reputation: 6933

Try stringify and it will show what object you are actually dealing with. It is obvious that the emails[index] is an object and not a string.

fetch('/emails/inbox')
.then(response => response.json())
.then(emails =>
{
    for (index = 0; index < emails.length; index++)
    {
        document.getElementById("emails-view").innerHTML += JSON.stringify(emails[index]);
    }
}

Upvotes: 3

Related Questions