Create jq json for slack bot

Update: I got this working and posted an answer.

I am trying to create a markdown block for a slack bot using jq inside of a bash script. Most of the tutorials I've found are for reading json but I am trying to create json.

I'm close but I'm still doing something wrong. This is the desired slack format, I've copied the relevant section below:

    "text": "Danny Torrence left a 1 star review for your property.",
    "blocks": [
            "type": "section",
            "text": {
                "type": "mrkdwn",
                "text": "Danny Torrence left the following review for your property:"

And here is a portion of my script:

FIRST_INNER_SECTION=$(jq -n --arg secType "mrkdwn" --arg textVal "Hi\nperson\n<@U12345789>" '{type: $secType, text: $textVal}')
FIRST_OUTER_SECTION=$(jq -n --arg secType "section" --arg textVal "$FIRST_INNER_SECTION" '{type: $secType, text: $textVal}')
MY_STR=$(jq -n --arg text "$FALLBACK_MESSAGE" --arg blocks "$FIRST_OUTER_SECTION" '{text: $text, blocks: [$blocks]}');
echo $MY_STR
curl -X POST -H 'Content-type: application/json' --data "$MY_STR"

I am getting an invalid blocks format error. I think it's due to creating multiple strings and trying to combine them with jq (seeing lots of slashes and newlines). I tried using different flags besides -n but they didn't work. I am going to try creating a mega string now but would prefer to split it up like I've done. Any help here?

Update with Megastring working. Would still like to find a way to format this better.

JSON_STRING=$( jq -n --arg fallbackText "Fallback message" --arg sectionType "section" --arg markdownType "mrkdwn" --arg textType "test" '{text: $fallbackText, blocks: [{type: $sectionType, text: {type: $markdownType, text: $textType}}]}')
curl -X POST -H 'Content-type: application/json' --data "$JSON_STRING"

Read more here:

Content Attribution

This content was originally published by Bix at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: