Search code examples
jsongroovy

Invalid payload - Slack API JSON


I am using a Groovy script to send a POST using the Slack API, at present I am getting invalid_payload returned and I think this is most likely due to the formatting of my JSON. I know the Slack API expects it JSON with double quotes but I can't seem to be able to pass a variable into the JSON object:

SUCCESS_MESSAGE = '{"attachments": [{"color": "#2A9B3A", "author_name": ${DEV_NAME}, "title": "Build Status", "title_link": ${BUILD_URL}, "text": "Successful Build" }]}'
def response = ["curl", "-X", "POST", "-H", "Content-Type: application/json", "-d", "${SUCCESS_MESSAGE}", "https://hooks.slack.com/services/${SLACK_WEBHOOK}"].execute().text

How should I correctly format my SUCCESS_MESSAGE var so I don't get the error?


Solution

    1. You need to quote your DEV_NAME and BUILD_URL variable expansions so the JSON string is valid.
    2. Your whole string needs to be enclosed in " instead of ' so the variables are actually expanded
    3. And you need to escape the " inside your string so they appear in your JSON string.

      SUCCESS_MESSAGE = "{\"attachments\": [{\"color\": \"#2A9B3A\", \"author_name\": \"${DEV_NAME}\", \"title\": \"Build Status\", \"title_link\": \"${BUILD_URL}\", \"text\": \"Successful Build\" }]}"`

    Alternatively you can generate the JSON in much nicer programmatic way. Which would be helpful if your notifications got a bit more complicated:

    def notification = [
      attachments: [
        [
          color: "#2A9B3A",
          author_name: DEV_NAME,
          title: "Build Status",
          title_link: BUILD_URL,
          text: "Successful Build"
        ]
      ]
    ]
    
    def response = ["curl", "-X", "POST", "-H", "Content-Type: application/json", "-d", JsonOutput.toJson(notification), "https://hooks.slack.com/services/${SLACK_WEBHOOK}"].execute().text