无效的有效负载-Slack API JSON [英] Invalid payload - Slack api JSON
问题描述
我正在使用groovy脚本通过松弛api发送POST,目前我正在返回 invalid_payload
,我认为这很可能是由于JSON格式所致,我知道松弛的api期望它带有双引号的JSON,但我似乎无法将变量传递到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 cant 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
有人知道我将如何正确格式化我的 SUCCESS_MESSAGE
变量,这样我就不会收到错误消息?
Does anyone know how I would correctly format my SUCCESS_MESSAGE
var so i dont get the error ?
谢谢
推荐答案
- 您需要引用
DEV_NAME
和BUILD_URL
变量扩展名,以便JSON字符串有效. - 您的整个字符串需要用
"
而不是'
括起来,以便实际上扩展变量 -
您需要在字符串中
escape
"
,以便它们出现在JSON字符串中.
- You need to quote your
DEV_NAME
andBUILD_URL
variable expansions so the JSON string is valid. - Your whole string needs to be enclosed in
"
instead of'
so the variables are actually expanded And you need to
escape
the"
inside your string so they appear in your JSON string.
SUCCESS_MESSAGE ="{\"附件\:[{\"颜色\:\"#2A9B3A \,\"作者名\:\" $ {DEV_NAME} \,\"标题\:\"Build Status \",\"title_link \":\"$ {BUILD_URL} \",\"text \":\"Successful Build \"}]}"`
SUCCESS_MESSAGE = "{\"attachments\": [{\"color\": \"#2A9B3A\", \"author_name\": \"${DEV_NAME}\", \"title\": \"Build Status\", \"title_link\": \"${BUILD_URL}\", \"text\": \"Successful Build\" }]}"`
或者,您可以通过更好的编程方式来生成JSON.如果您的通知变得更加复杂,这将很有帮助:
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
这篇关于无效的有效负载-Slack API JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!