简体   繁体   中英

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?

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)

You mean something like this:

 var data = `{"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 }`; $(function() { var result = $.parseJSON(data); $.each(result, function(i, item) { if (typeof item != "object") { alert(item); } else { $.each(item, function(i, obj) { alert(obj.ts); }); } }); }); 
   

Sample fiddle: https://jsfiddle.net/4v0x34b1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM