Yarh
Yarh

Reputation: 4607

how to build json without escaping new line?

I run jq from bash and all my new lines are escaped

release_message="\`\`\`a\na\n\`\`\`"

query=$(jq -n \
   --arg message $release_message \
   "{text:\$message}"
);    
echo "query $query"

result

query {
  "text": "```a\\na\\n```"
}

How to prevent extra escape from jq?

Upvotes: 0

Views: 774

Answers (2)

Aaron
Aaron

Reputation: 24812

You can either encode your input in JSON yourself or let jq do it

  • option 1 : encode yourself

    release_message='"```a\na\n```"'
    jq -n --argjson message "$release_message" '{text:$message}'
    # or :
    # echo "$release_message" | jq '{text:.}'
    

    Have bash produce a valid JSON string (note : quotes-enclosed), pass through the standard input or with --argjson.

  • option 2 : let jq encode the string

    release_message='```a
    a
    ```'
    jq --arg message "$release_message" '{text:$message}'
    # or :
    # echo "$release_message" | jq -R --slurp '{text:.}'
    

    Have bash produce the literal string, pass with --arg or specify --raw-input/-R to have the input encoded in JSON, plus --slurp so that the multiple lines are considered as a single string.

Upvotes: 1

peak
peak

Reputation: 116740

Since you're using bash, it's generally best to use single quotes unless you want string interpolation. Consider, for example:

release_message='```a\na\n```'

query=$(jq -n \
   --arg message "$release_message" \
   '{text: $message }'
);    

echo "query $query"

You might want to consider using $'....':

release_message=$'```a\na\n```'

Using gsub

Depending on what your actual goals are, you might want to use gsub, e.g.

release_message='```a\na\n```'

query=$(jq -n \
   --arg message "$release_message" \
   '{text: ($message | gsub("\\n";"\n")) }'
);    

echo "query $query"

produces:

query {
  "text": "```a\\na\\n```"
}

Upvotes: 0

Related Questions