Bix
Bix

Reputation: 928

Use newline with jq

I've seen a number of posts on this but can't figure out what I need exactly. I've tried -r and argjson among other things.

I need the newlines to remain as \n and not be escaped to \\n.

I'd also like to be able to use ``` for code blocks but it ignores that section of the string.

FALLBACK_MESSAGE="TEST MESSAGE - $HOSTNAME"
MARKDOWN_MESSAGE="TEST MESSAGE - $HOSTNAME \(0x0a) \(\n) Hi <@U12345789>\n```Can we do a\nmultiline code block```"
JSON_STRING=$( jq -nr \
    --arg fallbackMessage "$FALLBACK_MESSAGE" \
    --arg sectionType "section" \
    --arg markdownType "mrkdwn" \
    --arg textMessage "$MARKDOWN_MESSAGE" \
    '{
        text: $fallbackMessage, 
        blocks: [
            {
                type: $sectionType,
                text: {
                    type: $markdownType, 
                    text: $textMessage
                }
            }
        ]
    }')
echo $JSON_STRING

Outputs:

{ "text": "TEST MESSAGE - devDebug", "blocks": [ { "type": "section", "text": { "type": "mrkdwn", "text": "TEST MESSAGE - devDebug \\(0x0a) \\(\\n) Hi <@U12345789>\\n" } } ] }

Upvotes: 4

Views: 4807

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295315

Make sure your shell variables contain actual newlines, not \n sequences.

If you want bash to convert escape sequences in a string into the characters they refer to, printf %b can be used for this purpose.

#!/usr/bin/env bash

fallback_message="TEST MESSAGE - $HOSTNAME"
markdown_message="TEST MESSAGE - $HOSTNAME \(0x0a) \(\n) Hi <@U12345789>\n\`\`\`Can we do a\nmultiline code block\`\`\`"

# create markdown_message_unescaped with an unescaped version of markdown_message
printf -v markdown_message_unescaped %b "$markdown_message"

jq -n \
  --arg textMessage "$markdown_message_unescaped" \
  --arg fallbackMessage "$fallback_message" \
  --arg sectionType section --arg markdownType markdown '
    {
      text: $fallbackMessage, 
      blocks: [
        {
          type: $sectionType,
          text: {
                    type: $markdownType, 
                    text: $textMessage
                }
            }
        ]
    }'

...properly emits as output:

{
  "text": "TEST MESSAGE - YOUR_HOSTNAME",
  "blocks": [
    {
      "type": "section",
      "text": {
        "type": "markdown",
        "text": "TEST MESSAGE - YOUR_HOSTNAME (0x0a) (\n)\nHi <@U12345789>\n```\nCan we do a multiline code block\n```"
      }
    }
  ]
}

Upvotes: 5

Related Questions