Search code examples
javascriptjquerygetjsonslack-api

getJSON alert not returning anything - data issue?


I am having issues reading this data:

It looks like this:

{
  "ok": true,
  "messages": [
    {
      "text": "moo",
      "username": "bot",
      "type": "message",
      "subtype": "bot_message",
      "ts": "1448226157.000008"
    },
    {
      "text": "boo",
      "username": "bot",
      "type": "message",
      "subtype": "bot_message",
      "ts": "1448225998.000007"
    }
  ],
  "has_more": true
}

Here's the code:

$.getJSON("https://slack.com/api/channels.history?token=xxxx&channel=C0E&pretty=1", function(result){
            $.each(result, function(i, field){
                $("div").append(field + " ");
            });
        });

All I get is

[object object][object object]

How can I get the data to show properly?


Solution

  • Assuming:

    1. That's the full JSON
    2. You want to loop through the messages

    Your loop should be more like:

    $.each( result.messages,
      function( i, msg ) {
        $("div").append( msg.username + ": " + msg.text + " " );   
      }
    );
    

    (or whichever fields you wish to display)