Jamie
Jamie

Reputation: 291

Parsing JSON formatted Slack payload in Google Script

I'm trying to dig deeper into a nested Slack payload to get at some 'fields' I embedded in the original message.

I'm still not even sure this is even JSON.. Slack denies that they even support it.. but I have to process it as JSON?? anyhow maybe someone can illuminate this.

Anyhow.. this is my script to drill into the payload:

function doPost(e) {
  var payload = e.parameter.payload;
  var json = JSON.parse(payload);
  var attached = json["original_message"].attachments;
  ...

Which the var attached is:

{
   color=7CD197, callback_id=123, 
   text=Invite *Hello* to this slack?, id=1, 
   fields=[Ljava.lang.Object;@710f54d9, 
   fallback=Something went wrong.. try again, 
   actions=[Ljava.lang.Object;@67e92a25
}

to access the fields object I would expect to use the following syntax:

var field_value = attached.fields[0].value;

which I believe should be correct as I want to retrieve the first nested object (there can be more than one) of the fields object. The original message fields are as follows:

"fields": [
            {
                "title": "Name",
                "value": invitation_name,
                "short": true
            },
            {
                "title": "Email",
                "value": invitation_email,
                "short": true
            }
        ],

where invitation_name and invitation_email are passed values.

So given this logic as above I expect the var field_value = attached.fields[0].value; to return the passed value of invitation_name.. however I get the following:

TypeError: Cannot read property "0" from undefined.

The original incoming payload as from var payload = e.parameter.payload; does include the fields object.. but the JSON.parse turns it into fields=[Ljava.lang.Object;@710f54d9,..

https://www.mkyong.com/javascript/how-to-access-json-object-in-javascript/

gives an excellent rundown on how to drill in to a json file and I've used to good effect to get everything I want.. except now I can't dig in any further without generating an invalid return..

Upvotes: 0

Views: 1145

Answers (1)

Aquil4x
Aquil4x

Reputation: 26

Your var attachments is an array so to access fields[0].value in it you will need an index.

Try var field_value = attached[0].fields[0].value;

Or better:

var attached = json["original_message"].attachments[0]; var field_value = attached.fields[0].value;

Upvotes: 1

Related Questions